业务开发中,评分组件基本都是用element,antd这些框架的已经给我们封装好了现成的。现在手写一个原生的评分组件
效果![请添加图片描述](https://i-blog.csdnimg.cn/direct/739de76b0f8a42c280d1cdc8fc9c0032.gif)
代码实现
- 必要的css
.rating {
width: 600px;
margin: 60px auto;
text-align: center;
}
.rating img {
width: 30px;
height: 30px;
cursor: pointer;
}
h2{
text-align: left;
font-size: 24px;
}
- 静态页面
<div class="rating">
<h2>评分:</h2>
<ul id="list" class="order-list list-group">
<li class="list-group-item d-flex align-items-center">
<span>商品质量:</span>
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<span>
<em>0</em>分
</span>
</li>
<li class="list-group-item d-flex align-items-center">
<span>客服服务:</span>
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<span>
<em>0</em>分
</span>
</li>
<li class="list-group-item d-flex align-items-center">
<span>物流运输:</span>
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<span>
<em>0</em>分
</span>
</li>
<li class="list-group-item d-flex align-items-center">
<span>售后服务:</span>
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<img src="./images/s.png" alt="" srcset="">
<span>
<em>0</em>分
</span>
</li>
</div>
- 核心逻辑
window.onload = function () {
const oRating = document.getElementsByClassName('rating')[0];
const oLi = oRating.getElementsByTagName('li');
for (var p = 0; p < oLi.length; p++) {
const oImg = oLi[p].getElementsByTagName('img');
const oEm = oLi[p].getElementsByTagName('em');
const arr = [1, 2, 3, 4, 5]
let isClick = false;
let index = -1, scoreIndex = 0
for (var i = 0; i < oImg.length; i++) {
oImg[i].index = i
oImg[i].onmousemove = function () {
for (var j = 0; j <= this.index; j++) {
oImg[j].src = './images/s-active.png'
}
index = this.index
getScore()
}
oImg[i].onmouseout = function () {
for (var j = oImg.length - 1; j > scoreIndex; j--) {
oImg[j].src = './images/s.png'
}
}
oImg[i].onclick = function () {
isClick = true;
index = this.index;
scoreIndex = this.index;
for (var j = oImg.length - 1; j > this.index; j--) {
oImg[j].src = './images/s.png'
}
getScore()
}
}
oLi[p].onmouseout = function () {
if (isClick) {
for (var j = 0; j <= scoreIndex; j++) {
oImg[j].src = './images/s-active.png'
}
} else {
for (var j = 0; j < oImg.length; j++) {
oImg[j].src = './images/s.png'
}
}
index = isClick ? scoreIndex : -1
getScore()
}
getScore()
function getScore() {
oEm[0].innerHTML = arr[index] || 0
}
}
}