两个背景小片
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>半颗星评价效果</title>
</head>
<style>
.stardiv
{
color: #F4A460;
}
.stardiv:nth-child(n+3)
{
color: #008000;
}
/*======================================*/
.stardiv2
{
background: url(./image/star_bg.png) repeat-x;
height: 50px;
width: 240px;
background-color: #008000;
position: absolute;
}
.stardiv2::before
{
content: "";
background: url(image/star.png) repeat-x;
height: 100%;
width: 40%;
display: inline-block;
}
/*=======================================*/
.stardiv3
{
height: 50px;
width: 240px;
background: url(image/star_bg.png) repeat-x;
}
.stardiv3 .left_span
{
display: inline-block;
height: 50px;
width: 24px;
background: url(image/star.png) repeat-x;
}
</style>
<body>
<h3>整颗星实现</h3>
<div>
<span class="stardiv">★</span>
<span class="stardiv">★</span>
<span class="stardiv">★</span>
<span class="stardiv">★</span>
<span class="stardiv">★</span>
</div>
<br />
<br />
<h3>半颗星效果</h3>
<p>采用伪类元素的话,不好动态修改伪类元素的宽度(addRule或者insertRule)</p>
<div class="stardiv2" onclick="setValue(event)">
</div>
<br />
<br />
<p>方式2:父级div用无色的做背景,子div用有色的做背景,修改子div的宽度实现。原理相同</p>
<div class="stardiv3" onclick="setMainValue(event)">
<span class="left_span"></span>
</div>
<script type="text/javascript">
function setValue(e)
{
console.log(e.offsetX,e.offsetY)
let max_w = 240;
let pre = "width:" + e.offsetX*100/240 + "%";
console.log(pre);
var style = document.createElement("style");
document.head.appendChild(style);
sheet = style.sheet;
//sheet.addRule('.stardiv2:before',pre);
sheet.insertRule(`.stardiv2:before{${pre}}`, 0); //
}
function setMainValue(e)
{
console.log(e.offsetX,e.offsetY)
let max_w = 240;
let pre = "width:" + e.offsetX*100/240 + "%";
console.log(pre);
let leftspan = document.getElementsByClassName("left_span");
leftspan[0].style.width = e.offsetX*100/240 + "%";
}
</script>
</body>
</html>