DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> CSS入門知識 >> CSS進階教程 >> 用CSS實現動態顯示的五角星級效果
用CSS實現動態顯示的五角星級效果
編輯:CSS進階教程     

用純css打造星級評分效果正在被越來越多地應用在網絡RIA中,結合ajax等技術,可以渲染出很出色的視覺效果和很棒的用戶體驗,在這篇文章開始之前,大家可以先去cssheaven感受一下。

最近由於項目需要,我在網上找了很多css星級評分的例子和說明,但是發現大多數都是翻譯國外的文章,而且解釋得並不是非常清楚,所以我決定自己來做一個總結,也希望能夠給大家一些幫助。

首先用中文寫一下這個效果的算法:
1. 使用背景圖片的位置切換來獲得星級效果;

2. 整個效果最關鍵的地方就是“三層理論”,整個效果分為三層——空分層、分數層和打分層,三層的布局均為absolute,以避免ul本身自帶的相對布局(當然用div也可以獲得同樣效果);
3. 空分層就是使用背景圖片中的“空星”作為背景,並橫向平鋪;
4. 分數層的寬度等於(分數*圖片寬度)得到的數值,並且使用背景圖片中的“分數星(例子中為黃色)”作為背景橫向平鋪;
5. 打分層就是將5個空鏈接置於5個星星的位置上(寬度要和背景圖片吻合),並將5個a:hover的背景設為“打分星(這裡為綠色)”,寬度設為星數*圖片寬度,left為0(靠左,這樣結合a:hover不同的寬度就可以出現打分效果),垂直坐標小於a的垂直坐標(以確保當前a:hover不會遮擋住其他鏈接);

也許上面這段文字你看得有些生澀,沒有關系,讓我們結合css代碼來看看解決辦法

<ul class="star-rating">
<li class="current-rating">Currently 3.5/5 Stars.</li>
<li><a href="#" title="1 star out of 5" class="one-star">1</a></li>
<li><a href="#" title="2 stars out of 5" class="two-stars">2</a></li>
<li><a href="#" title="3 stars out of 5" class="three-stars">3</a></li>
<li><a href="#" title="4 stars out of 5" class="four-stars">4</a></li>
<li><a href="#" title="5 stars out of 5" class="five-stars">5</a></li>
</ul>

<style>
.star-rating{/*這裡是空分層,用來顯示空星星*/
list-style:none;
margin: 0px;
padding:0px;
width: 150px;
height: 30px;
position: relative;
background: url(star_rating2.gif) top left repeat-x;/*空星星位於背景圖片的頂層,將其設為背景並橫向平鋪*/
}
.star-rating li{/*設置li的浮動屬性*/
padding:0px;
margin:0px;
/**/
float: left;
/* */
}
.star-rating li a{/*設置a的布局為絕對布局和垂直坐標並隱藏a中文本使其成為空鏈接*/
display:block;
width:30px;
height: 30px;
text-decoration: none;
text-indent: -9000px;
z-index: 20;
position: absolute;
padding: 0px;
}
.star-rating li a:hover{/*設置a:hover的背景圖片為打分星/垂直坐標/left為0,注意垂直坐標一定要小於a的垂直坐標*/
background: url(star_rating2.gif) left center;
z-index: 2;
left: 0px;
}

/*以下5個class用來設置5個鏈接的位置和hover的寬度*/
.star-rating a.one-star{
left: 0px;
}
.star-rating a.one-star:hover{
width:30px;
}
.star-rating a.two-stars{
left:30px;
}
.star-rating a.two-stars:hover{
width: 60px;
}
.star-rating a.three-stars{
left: 60px;
}
.star-rating a.three-stars:hover{
width: 90px;
}
.star-rating a.four-stars{
left: 90px;
}
.star-rating a.four-stars:hover{
width: 120px;
}
.star-rating a.five-stars{
left: 120px;
}
.star-rating a.five-stars:hover{
width: 150px;
}

.star-rating li.current-rating{/*設置分數層的背景和寬度並隱藏文本*/
background: url(star_rating2.gif) left bottom;
position: absolute;
height: 30px;
width:105px;
display: block;
text-indent: -9000px;
z-index: 1;
}
</style>

 

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved