JavaScript实现5星好评
代码直接就上了,有什么问题可以问我
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body,
a,
h1,
h2,
h3,
h4,
h5,
h6,
p,
a,
b,
i,
em,
ul,
ol,
li,
strong,
table,
th,
tr,
td,
img,
form,
input,
button,
select,
option,
textarea {
margin: 0;
padding: 0;
}
.body {
text-align: center;
margin: 10px auto;
width: 800px;
height: 64px;
background-color: aqua;
}
span {
display: inline-block;
width: 40px;
height: 40px;
/* border: 1px solid red; */
}
span.star {
background: url(https://s3.ax1x.com/2020/11/21/Dl492V.png) no-repeat;
/* cursor: pointer; */
/* vertical-align: -2px; */
/*span为行内元素,不能直接设置宽高,转换成block*/
}
span.star-off {
background-position: -40px 0;
}
</style>
</head>
<body>
<!-- 图片精灵技术----网站上有许多的icon图片,比如说打评分等等,如果每个都单独做的话,每次请求都会对服务器造成很大的压力,所以就把所有的
图标做在一起了
-->
<div class="body">
<div>
<span style="width: 150px;">请选择您的评价:</span>
<span class="star star-off"></span>
<span class="star star-off"></span>
<span class="star star-off"></span>
<span class="star star-off"></span>
<span class="star star-off"></span>
<span id="pingjia"></span>
</div>
</div>
<script>
//获取对象
// var div = document.querySelector("div");
// console.log(div);
// var span = document.querySelectorAll(".star")
// console.log(span);
var star = document.getElementsByClassName("star");
var pingjia = document.querySelector("#pingjia");
var pingjias = ["很差","较差","一般","良好","很好"];
var len = star.length;
onoff = true; //开关,判断是否点击,点击后不执行移入移出事件
for(var i = 0;i < len;i++){
//绑定鼠标移入 移出 点击
star[i].index = i;
star[i].onmouseover = function(){
if(onoff){
var num = this.index;
pingjia.innerHTML = pingjias[num];
for(var i = 0;i <= num;i++){
star[i].style.backgroundPosition = "0 0";
}
}
}
star[i].onmouseout = function(){
if(onoff){
var num = this.index;
pingjia.innerHTML = "";
for(var i = 0;i<=num;i++){
star[i].style.backgroundPosition = "-40px 0";
}
}
}
star[i].onclick =function() {
onoff=false;
pingjia.innerHTML = "";
for(var j = 0;j < len;j++){
star[j].style.backgroundPosition = "-40px 0";
}
var num = this.index;
pingjia.innerHTML = pingjias[num];
for(var i = 0;i <= num;i++){
star[i].style.backgroundPosition = "0 0";
}}
}
</script>
</body>
</html>
我图片传到了图床了,所以可以复制后直接使用的。
博客文章跳转–Csdn
个人博客跳转–Datehoer的Blog