下面為引用,源代碼有點問題,自己修改了一下。先做記錄,回頭再細修。
引用部分,但代碼有問題
http://www.ptbird.cn/css-background-attachment--fiexed-no-work.html
一、問題
一個網站中使用了 background-attachment:fixed;
來控制背景圖不隨內容的滾動而滾動,使其固定大小。
我的背景圖是作用在 body
上的。
在PC端可以起作用和一些安卓的機器上能夠起作用,但是在iphone上沒有效果。
二、原因
網上看了很多,都只說怎么解決,解決方法也有好用和不好用的,但是沒有人解釋為什么。
在 stackoverflow 上查找的時候發現的原因如下:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
固定背景導致重繪的成本很高,並且滾動表現也不盡人意,所以在一些移動端是被禁止的。
三、解決
移動無法直接應用 background-attachment
,可以曲線救國。
有的推薦使用 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的背景實際上是不顯示的。
可以在新標簽中打開圖片查看詳細內容