返回
星星打分效果
前端
2023-10-17 20:54:27
在很多网站或应用程序中,我们经常会看到星星打分的效果。用户可以通过点击星星来对某个产品、服务或内容进行评分。这种打分方式非常直观、简单,而且还可以让用户更方便地表达自己的意见。
效果演示
我们先来看一下星星打分效果是如何实现的。
[图片]
如上图所示,用户可以通过点击星星来对某个产品或服务进行评分。当用户点击一颗星星时,这颗星星就会变为实心。用户还可以通过再次点击这颗星星来取消评分。
代码片段
<div class="star-rating">
<input type="radio" id="star1" name="rating" value="1">
<label for="star1">1</label>
<input type="radio" id="star2" name="rating" value="2">
<label for="star2">2</label>
<input type="radio" id="star3" name="rating" value="3">
<label for="star3">3</label>
<input type="radio" id="star4" name="rating" value="4">
<label for="star4">4</label>
<input type="radio" id="star5" name="rating" value="5">
<label for="star5">5</label>
</div>
.star-rating {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.star-rating input {
display: none;
}
.star-rating label {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating input:checked ~ label {
color: #ffcc00;
}
const starRating = document.querySelector('.star-rating');
starRating.addEventListener('click', (event) => {
const rating = event.target.value;
// Do something with the rating value
});
背景
星星打分效果是一种非常常见的用户交互元素。它经常被用于网站、应用程序和游戏等各种类型的软件中。星星打分效果之所以如此受欢迎,主要是因为它非常直观、简单,而且还可以让用户更方便地表达自己的意见。
具体实现
星星打分效果的具体实现步骤如下:
- 在 HTML 代码中创建一个
<div>
元素,并为其添加一个类名(例如:star-rating
)。 - 在
<div>
元素中添加一组<input>
元素。这些<input>
元素的类型为radio
,并且都有一个相同的name
属性(例如:rating
)。 - 在
<input>
元素中添加一个value
属性,用于指定该<input>
元素对应的分值。 - 在
<input>
元素中添加一个id
属性,用于与<label>
元素关联。 - 在
<div>
元素中添加一组<label>
元素。这些<label>
元素用于显示星星图标。 - 为
<label>
元素添加一个for
属性,用于与<input>
元素关联。 - 为
<label>
元素添加一个cursor: pointer;
样式,以便用户可以通过点击<label>
元素来选择对应的<input>
元素。 - 为
<input>
元素和<label>
元素添加样式,以实现星星打分效果。
总结
星星打分效果是一种非常常见的用户交互元素。它经常被用于网站、应用程序和游戏等各种类型的软件中。星星打分效果之所以如此受欢迎,主要是因为它非常直观、简单,而且还可以让用户更方便地表达自己的意见。
本文介绍了星星打分效果的实现步骤,希望对大家有所帮助。