先看看效果
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>评分</title>
</head>
<body>
<div class="star">
</div>
<div class="text"></div>
<!-- 引入jquery -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./jQuery.js"></script>
</body>
</html>
JS
let dataArr = ["很差", "较差", "一般", "满意", "非常满意"];
function render() {//渲染页面
let str = ''
dataArr.forEach((item, index) => {//自定义下标
str += `<img src="./starimg/empty.png" data-index="${index}">`
})
$('.star').html(str);
}
render();
//鼠标移入事件
$('.star').on('mouseover', 'img', mouseover)
function mouseover() {
$(`img:lt(${this.dataset.index - 0 + 1})`).prop('src', `./starimg/shining.png`);
$(`img:gt(${this.dataset.index})`).prop('src', `./starimg/empty.png`);
$('.text').html(dataArr[this.dataset.index]);
}
let state = false;
//移出事件
$('.star').on('mouseout', 'img', mouseout)
function mouseout() {
$('img').map(() => {
($(this).attr('class') == 'click') ? state = true : ``;
console.log(state);
})
if (!state) {
$(`img`).prop('src', `./starimg/empty.png`);
$('.text').html('')
} else {
$('.click').prop('src', `./starimg/shining.png`);
$(`img:lt(${$('.click').attr('data-index')})`).prop('src', `./starimg/shining.png`);
$(`img:gt(${$('.click').attr('data-index')})`).prop('src', `./starimg/empty.png`);
$('.text').html(dataArr[($('.click').attr('data-index')) - 0]);
}
}
//点击
$('.star').on('click', 'img', click)
function click() {
$('img').removeAttr('class')
$(`img:lt(${this.dataset.index - 0 + 1})`).prop('src', `./starimg/shining.png`);
$(this).prop('class', 'click');
}