css兩種動態顯示星星等級的比較(一星、兩星、三星、四星、五星)


以下是顯示后的圖片,相信在很多網站上都能看到這種效果,目前我知道兩種實現方式

1、background-position加上一張圖片

    圖片:http://www.brookstone.com/webassets/pwr/engine/images/stars.gif

  

 

 1 <!DOCTYPE html>
 2 <html>
 3 
 4   <head>
 5     <link rel="stylesheet" href="style.css">
 6     <script src="script.js"></script>
 7     <style>
 8            .star{
 9              height: 20px;
10              line-height: 20px;
11              width: 112px;
12              background-image: url('http://www.brookstone.com/webassets/pwr/engine/images/stars.gif');
13              background-position:0 -69px;
14              background-repeat:no-repeat;
15            }
16 
17     </style>
18   </head>
19 
20   <body>
21     <div class="star"></div>
22     
23 
24   </body>
25 
26 </html>

這是最簡單的background-position定位,不過如果還是覺得stars.gif比較大,可以用第二種方法,不過在使用第二種方法之前必須將stars.gif用photoshop裁剪下,裁剪成兩個圖片,沒有金色星星(5顆灰色星星)的和5金色星的兩張圖片,其他各類星星的都舍去掉,當然我比較懶,下面的demo圖片沒有用工具裁剪,直接用的原stars.gif。

2、CSS clip 屬性

     瀏覽器支持

    所有主流瀏覽器都支持 clip 屬性。

    clip 屬性剪裁絕對定位元素。

    clip::rect (top, right, bottom, left)

    position:absolute 這個必須有

  

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <style>

           .star1{
             margin:10px 0 0 0;
             height: 20px;
             line-height: 20px;
             width: 112px;
             background-image: url('http://www.brookstone.com/webassets/pwr/engine/images/stars.gif');
             background-position:0 0;
           }
           .star1 .inner{
             height: 20px;
             line-height: 20px;
             width: 112px;
             background-image: url('http://www.brookstone.com/webassets/pwr/engine/images/stars.gif');
             background-position:0 -230px;
             position:absolute;
             clip:rect(0px,61px,21px,0px);
           }
    </style>
  </head>

  <body>
    
    <div class="star1">
      <div class='inner'></div>
    </div>
  </body>

</html>

這個用rect裁剪的好處是即使你想要1.2顆星星也是可以的,只需要改下clicp的rect第二個參數就行了,61px改為27.6px,clip:rect(0px,27.6px,21px,0px);

計算方式 一個星星23px,1.2顆星星:23+23/10*2=27.6,顯示效果:

對比第一種,stars.gif這個圖片得不斷添加各類值得星星,好處顯而易見,第二種靈活圖片小,減少傳輸開銷。

備注: .star1樣式里面的圖片應該是5顆灰色星星,.star1 .inner里的圖片應該是5顆金色星星

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM