【发布时间】:2016-06-21 17:51:37
【问题描述】:
我创建了一个 5 星评级系统。我的 CSS 设置为显示固定在屏幕上的灰色背景星星。当悬停在蓝色星星上时,虽然这些星星居中并向外延伸,例如当我选择 1 颗星星时,中间的星星变成金色而不是最左边的灰色星星,同样如果我选择 2 颗星星,两颗金色星星出现在第二和第四颗灰色星星,灰色星星在背景中仍然可见。这看起来很不整洁。
谁能告诉我如何更改我的代码以将实际选中的星星变成金色?
我的星星图片是 stars.png,在一张图片中分别有一个灰色、蓝色和金色的星星。
我对 css 的了解有限。我曾尝试一一更改 css 的多个组件,例如宽度或像素,但无济于事。
这是我的 CSS。
form .stars {
background: url("stars.png") repeat-x 0 0;
width: 150px;
margin: 0 auto;
}
form .stars input[type="radio"] {
position: absolute;
opacity: 0;
filter: alpha(opacity=0);
}
form .stars input[type="radio"].star-5:checked ~ span {
width: 100%;
}
form .stars input[type="radio"].star-4:checked ~ span {
width: 80%;
}
form .stars input[type="radio"].star-3:checked ~ span {
width: 60%;
}
form .stars input[type="radio"].star-2:checked ~ span {
width: 40%;
}
form .stars input[type="radio"].star-1:checked ~ span {
width: 20%;
}
form .stars label {
display: block;
width: 30px;
height: 30px;
margin: 0!important;
padding: 0!important;
text-indent: -999em;
float: left;
position: relative;
z-index: 10;
background: transparent!important;
cursor: pointer;
}
form .stars label:hover ~ span {
background-position: 0 -30px;
}
form .stars label.star-5:hover ~ span {
width: 100% !important;
}
form .stars label.star-4:hover ~ span {
width: 80% !important;
}
form .stars label.star-3:hover ~ span {
width: 60% !important;
}
form .stars label.star-2:hover ~ span {
width: 40% !important;
}
form .stars label.star-1:hover ~ span {
width: 20% !important;
}
form .stars span {
display: block;
width: 0;
position: relative;
top: 0;
left: 0;
height: 30px;
background: url("stars.png") repeat-x 0 -60px;
-webkit-transition: -webkit-width 0.5s;
-moz-transition: -moz-width 0.5s;
-ms-transition: -ms-width 0.5s;
-o-transition: -o-width 0.5s;
transition: width 0.5s;
}
【问题讨论】:
-
嗯,你能把行号去掉吗?
-
嗨@JacobGray。我已按要求删除了行号。顺便说一下,它们不在我的实际代码中
-
本质上归结为更改
background-position属性。您移动背景图像,以便显示您想要的星星的“状态”。我无法提供确切的代码,因为我不知道你的星图长什么样。 -
这是一个非常可靠的示例,它使用
input:checked ~ label:before将样式应用于当前选中的收音机和任何“较低”值的收音机。 codepen.io/lsirivong/pen/ekBxI -
这里是同一个例子,但我对其进行了修改以简化它。 jsfiddle.net/ve3m7vxe
标签: css rating-system