最近發現css
的一個背景圖片的屬性,可以實現一個很酷璇的效果,根據效果,我給它命名爲王者換膚,下面我們來看一下它的實現方式。
-
css3參考手冊 的背景與邊框目錄裏面,有一個介紹
background-attachment
屬性的,它的值有3個,分別是fixed,scroll,local
,他們分別代表的意義如下:
- 首先測試一下
scroll
屬性的效果,頁面結構如下:
<div class="wrap item1">
<p>
Information1
</p>
</div>
- 樣式如下:
.wrap {
width: 100%;
height: 800px;
overflow: scroll;
background-repeat: no-repeat;
background-position: left center;
background-size: 100% auto;
background-color: black;
background-image: url(images/th1.jpg);
<!-- scroll -->
background-attachment: scroll;
}
p {
width: 100%;
height: 1000px;
background: rgba(255,255,255,0.5);
font-size: 30px;
text-align: center;
line-height: 100px;
font-weight: 700;
color:#2d2a2a;
position: relative;
}
.item1 p{
margin-top: 50px;
}
- 效果如下:
元素髮生滾動,背景圖片沒有跟隨滾動,那我們再看一下
local
屬性的效果,DOM
結構不用變,只修改屬性值如下:
.wrap {
width: 100%;
height: 800px;
overflow: scroll;
background-repeat: no-repeat;
background-position: left center;
background-size: 100% auto;
background-color: black;
background-image: url(images/th1.jpg);
<!--local -->
background-attachment: local;
}
- 效果如下:
元素滾動,背景圖片跟隨滾動,我們再看一下
fixed
屬性的效果,DOM
結構不用變,只修改屬性值如下:
.wrap {
width: 100%;
height: 800px;
overflow: scroll;
background-repeat: no-repeat;
background-position: left center;
background-size: 100% auto;
background-color: black;
background-image: url(images/th1.jpg);
<!--fixed -->
background-attachment: fixed;
}
- 效果如下:
背景圖片不隨元素滾動,當元素即將滾動出視口,其他
DOM
結構出現,背景圖片也未發生移動,看起來像是被其他元素遮擋了一樣,其實是元素隨着頁面的滾動,部分內容已經不在視口的範圍,所以不再顯示,並不是被其他元素遮擋了。這個就是fixed
的效果。一個元素是這樣的效果,如果頁面裏面多放幾個元素,屬性都設置爲fixed
,會是什麼效果呢?頁面佈局如下:
<div class="wrap item1">
<p>
Information1
</p>
</div>
<div class="wrap item2">
<p>
Information2
</p>
</div>
<div class="wrap item3">
<p>
Information3
</p>
</div>
<div class="wrap item4">
<p>
Information4
</p>
</div>
<div class="wrap item5">
<p>
Information5
</p>
</div>
- 樣式如下:
.wrap{
width: 100%;
height: 800px;
background-repeat: no-repeat;
background-position: left center;
background-size: 100% auto;
background-color: black;
overflow: scroll;
/*fixed*/
background-attachment: fixed;
}
p{
width: 100%;
height:100px;
background: rgba(255,255,255,0.5);
font-size: 30px;
text-align: center;
line-height: 100px;
font-weight: 700;
color:#2d2a2a;
position: relative;
}
.item1 p{
margin-top: 50px;
}
.item1{
background-image: url(images/th1.jpg);
}
.item2{
background-image: url(images/th2.jpg);
}
.item3{
background-image: url(images/th3.jpg);
}
.item4{
background-image: url(images/th4.jpg);
}
.item5{
background-image: url(images/th5.jpg);
}
- 效果如下:
- 頁面看起來就像在動態切換背景一樣,我稱之爲王者換膚。