做五个星星鼠标移动星星变亮
时间: 2024-02-15 13:14:06 浏览: 143
以鼠标顶点为中心,随鼠标移动,会改变颜色的五角星
4星 · 用户满意度95%
以下是一个简单的 HTML、CSS 和 JavaScript 代码示例,可以实现五个星星,当鼠标移动到星星上时,星星变亮。
HTML 代码:
```html
<div class="rating">
<span class="star" data-rating="1"></span>
<span class="star" data-rating="2"></span>
<span class="star" data-rating="3"></span>
<span class="star" data-rating="4"></span>
<span class="star" data-rating="5"></span>
</div>
```
CSS 代码:
```css
.rating {
display: inline-block;
font-size: 0;
height: 20px;
position: relative;
width: 100px;
}
.star {
cursor: pointer;
display: inline-block;
font-size: 20px;
height: 20px;
margin-right: 4px;
position: relative;
width: 20px;
}
.star:before {
content: "\2605";
position: absolute;
left: 0;
top: 0;
}
.star:hover:before,
.star:hover ~ .star:before {
content: "\2605";
color: gold;
}
.star:hover:before {
z-index: 1;
}
```
JavaScript 代码:
```javascript
const stars = document.querySelectorAll('.star');
const rating = document.querySelector('.rating');
rating.addEventListener('click', function(e) {
const starClicked = e.target.closest('.star');
if (starClicked) {
const ratingValue = starClicked.dataset.rating;
alert(`You rated this ${ratingValue} stars.`);
}
});
rating.addEventListener('mousemove', function(e) {
const starUnderMouse = e.target.closest('.star');
if (starUnderMouse) {
const ratingValue = starUnderMouse.dataset.rating;
stars.forEach(function(star) {
if (star.dataset.rating <= ratingValue) {
star.style.color = 'gold';
} else {
star.style.color = 'gray';
}
});
} else {
stars.forEach(function(star) {
star.style.color = 'gray';
});
}
});
```
这个代码可以实现当鼠标移动到星星上时,星星变亮,当鼠标点击星星时,弹出一个提示框显示所选的星级评价。您可以根据自己的需求进行修改和定制。
阅读全文