这是我的代码,我想在其中使用JavaScriptHTML和CSS进行简单的星级评定。
var numbersDiv = document.getElementById("23");
var aa = document.createElement("div");
aa.className = "rating";
for (let i = 0; i < 5; i++) {
var tempStar = document.createElement("input");
tempStar.setAttribute("type", "radio");
tempStar.setAttribute("name", "star");
var tempStarId = "star" + i;
tempStar.id = tempStarId;
var tempLabel = document.createElement("label");
tempLabel.setAttribute("for", tempStarId);
aa.appendChild(tempStar);
aa.appendChild(tempLabel);
}
numbersDiv.appendChild(aa);
.rating {
display: flex;
}
.rating input {
display: none;
}
.rating label {
display: block;
cursor: pointer;
width: 50px;
background: #ccc;
}
.rating label:before {
content: "★";
position: relative;
font-family: fontAwesome;
display: block;
font-size: 50px;
color: #101010;
}
.rating label:after {
content: "★";
position: absolute;
font-family: fontAwesome;
display: block;
font-size: 50px;
color: #1f9cff;
top: 0;
}
.rating label:hover:after,
.rating label:hover~label:after,
.rating input:checked~label:after {
opacity: 1;
}
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/fontawesome.min.css" rel="stylesheet" />
</head>
<body>
<div id="23"></div>
</body>
</html>
有几个问题:
after
恒星略高于前恒星- 当我点击时,后星不会正常工作。(它们应该如何工作:当我点击一颗黑色的星星时,它会变成蓝色(
我在互联网上看到了这段代码,但由于某种原因,它根本不起作用。有人知道如何解决这个问题吗?
(为了记录在案,我在网上看到的视频是这样的:https://www.youtube.com/watch?v=Ep78KjstQuw)
您缺少两个重要的CSS选项:
-
您的标签需要为
position: relative;
,因为星星将相对于标签的坐标定位在标签内。缺少的position: relative;
导致星号与正文元素对齐,因此位于页面顶部。 -
你们的恒星从来没有
opacity: 0;
集合,因此总是可见的。
var numbersDiv = document.getElementById("23");
var aa = document.createElement("div");
aa.className = "rating";
for (let i = 0; i < 5; i++) {
var tempStar = document.createElement("input");
tempStar.setAttribute("type", "radio");
tempStar.setAttribute("name", "star");
var tempStarId = "star" + i;
tempStar.id = tempStarId;
var tempLabel = document.createElement("label");
tempLabel.setAttribute("for", tempStarId);
aa.appendChild(tempStar);
aa.appendChild(tempLabel);
}
numbersDiv.appendChild(aa);
.rating {
display: flex;
}
.rating input {
display: none;
}
.rating label {
/* Added Position Relative*/
position: relative;
display: block;
cursor: pointer;
width: 50px;
background: #ccc;
}
.rating label::before {
content: "★";
position: relative;
font-family: fontAwesome;
display: block;
font-size: 50px;
color: #101010;
}
.rating label::after {
content: "★";
position: absolute;
font-family: fontAwesome;
/* Set default Opacity to 0*/
opacity: 0;
display: block;
font-size: 50px;
color: #1f9cff;
top: 0;
}
.rating label:hover::after,
.rating label:hover~label::after,
.rating input:checked~label::after {
opacity: 1;
}
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/fontawesome.min.css" rel="stylesheet" />
</head>
<body>
<div id="23"></div>
</body>
</html>