css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

时间:2023-03-09 06:55:54
css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

原文:css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

以下是显示后的图片,相信在很多网站上都能看到这种效果,目前我知道两种实现方式

css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

1、background-position加上一张图片

图片:http://www.*stone.com/webassets/pwr/engine/images/stars.gif

css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

 <!DOCTYPE html>
<html> <head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style>
.star{
height: 20px;
line-height: 20px;
width: 112px;
background-image: url('http://www.*stone.com/webassets/pwr/engine/images/stars.gif');
background-position:0 -69px;
background-repeat:no-repeat;
} </style>
</head> <body>
<div class="star"></div> </body> </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.*stone.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.*stone.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,显示效果:css两种动态显示星星等级的比较(一星、两星、三星、四星、五星)

对比第一种,stars.gif这个图片得不断添加各类值得星星,好处显而易见,第二种灵活图片小,减少传输开销。

备注: .star1样式里面的图片应该是5颗灰色星星,.star1 .inner里的图片应该是5颗金色星星