background-attachment: fixed 在iphone设备失效的解决

下面为引用,源代码有点问题,本身修改了一下。先作记录,回头再细修。

引用部分,但代码有问题javascript

http://www.ptbird.cn/css-background-attachment--fiexed-no-work.htmlcss

1、问题

一个网站中使用了 background-attachment:fixed; 来控制背景图不随内容的滚动而滚动,使其固定大小。html

个人背景图是做用在 body 上的。java

在PC端能够起做用和一些安卓的机器上可以起做用,可是在iphone上没有效果。web

2、缘由

网上看了不少,都只说怎么解决,解决方法也有好用和很差用的,可是没有人解释为何。iphone

在 stackoverflow 上查找的时候发现的缘由以下:网站

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.url

固定背景致使重绘的成本很高,而且滚动表现也不尽人意,因此在一些移动端是被禁止的。spa

3、解决

移动没法直接应用 background-attachment ,能够曲线救国。code

有的推荐使用 javascript 去计算固定位置的,不过我采用的是 css 直接来控制,经过 :before 来控制:

body{
    background-image: url(../img/wxfwh_bg_body.jpg);
    background-repeat: no-repeat;
    background-size:cover;
    -webkit-background-size: cover !important; 
    -moz-background-size: cover !important; 
    -o-background-size: cover; 
    background-attachment:fixed;
    z-index: -1;
}
body:before{
    content: "";
    position: fixed;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-image: inherit;
    -webkit-background-size: cover!important;
    -o-background-size: cover;
    background-size: cover!important;
}

 

 
 

这个回答的地址以下:

stackoverflow 的回答中使用的 height 的单位是 vh,相对于窗口的单位,100vh 天然是整个窗口,不过我由于做用在 body 上,因此用的是 height:100%

原理:

1. 使用 background-position:-9999px,-9999px 来隐藏原来的body的背景图

2. 使用 :before 在body以前添加内容

3. 实际上 :before 添加的内容中 background-image:inhert使用的是body的背景图,而且使用 fixed 定位,宽高为100%.

4. 将 :before 的z-index 设置为 -1 ,置于其余内容之下,这样子,会显示body:before的背景,body的背景其实是不显示的。

n-1.jpg

能够在新标签中打开图片查看详细内容

相关文章
相关标签/搜索