用 HTML 和 CSS 制作的五角星评分小部件
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="center">
<div class="stars">
<input type="radio" id="five" value="5" name="abc">
<!-- 这几个input的name值一定要相等,才能保持五个钮,每次只能点一个,达到单选的效果 -->
<label for="five"></label>
<input type="radio" id="four" value="4" name="abc">
<label for="four"></label>
<input type="radio" id="three" value="3" name="abc">
<label for="three"></label>
<input type="radio" id="two" value="2" name="abc">
<label for="two"></label>
<input type="radio" id="one" value="1" name="abc">
<label for="one"></label>
<div class="result"></div>
</div>
</div>
</body>
</html>
CSS:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.stars input {
display: none;
}
.stars label {
float: right;
/* 假如点击三颗星,从左边开始点 */
color: gainsboro;
font-size: 60px;
margin: 0 5px;
text-shadow: 1px 1px #bbb;
cursor: pointer;
transition: 0.2s;
}
.stars label::before {
content: '★';
}
.stars input:checked~label {
color: yellow;
text-shadow: 1px 1px #c60;
}
.stars:not(:checked)>label:hover,
.stars:not(:checked)>label:hover~label {
color: yellow;
}
.stars .result::before {
position: absolute;
content: '';
left: 50%;
transform: translateX(-50%);
bottom: 300px;
font-size: 30px;
color: gold;
display: none;
}
.stars input:checked~.result::before {
display: block;
}
.stars #five:checked~.result::before {
content: "i love it";
}
.stars #four:checked~.result::before {
content: 'i like it';
}
.stars #three:checked~.result::before {
content: 'it is good';
}
.stars #two:checked~.result::before {
content: 'i do not like it';
}
.stars #one:checked~.result::before {
content: 'i hate it';
}
----------------------------------------------------------------------------------------------------
总结:
-
not:()伪类的用法:
https://developer.mozilla.org/zh-CN/docs/Web/CSS/:not -
刚开始练习这个demo的时候,没把input的type当回事,因为之前做过
使用 HTML & CSS 制作左侧滑动导航条
这个demo,所以直接就把input的type设定为checkbox了,发现选定五角星的时候,只要选定#five,那么无论点击那颗五角星,五颗星,都会黄,因为checkbox的特性就是点击选中,必须再点击选中的checkbox才能取消,而
’使用 HTML & CSS 制作左侧滑动导航条‘这个案例,就只有打开,关闭的状态,且只用了一个input,所以type设置为checkbox较为合适,而这里不合适。然后我看了视频才知道,原作者把所有的input的type设置为了radio,单单这样还不行,因为radio选中之后,再点击选中的是不能取消的,但是我们可以把所有input 用name统一,这样一排radio按钮,选择一个,另一个则会取消选择状态,达到单选的目的。