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

能夠在新標籤中打開圖片查看詳細內容

相關文章
相關標籤/搜索