用CSS實現評星等級顯示效果。

來源:互聯網
上載者:User

用純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>

看完這些,我相信你應該明白了其中的原理了吧,如果還是不明白可以給我留言,或許還是我的文章寫得不夠好:)

學習資料:

http://www.jluvip.com/works/css/starvote/index2-1.html



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.