对当前元素的悬停效果不起作用

时间:2017-05-20 15:29:40

标签: html css rating

我正在实现一个简单的CSS评级小部件。到目前为止一切正常,但我面对这个简单的问题。 悬停在当前星上时,它不会改变星的颜色,但是如果我点击当前星,它会按预期工作。

我想这就是问题所在。

.rating label.rate:hover ~ label.rate:before {
     color: #FD4;
}



div.rating {
    display: inline-block;
}

.rating input.rate { 
    display: none; 
}

.rating label.rate {
    float: right;
    padding: 10px;
    font-size: 50px;
    color: #444;
}

.rating label.rate:hover ~ label.rate:before {
    color: #FD4;
}

.rating input.rate:checked ~ label.rate:before {
    color: #FD4;
}
    
label.rate:before {
    content: '*';
}
   

<div class="rating">        
    <input class="rate" id="star-5" type="radio" name="rate" value="5"/>
    <label class="rate" for="star-5"></label>
    <input class="rate" id="star-4" type="radio" name="rate" value="4"/>
    <label class="rate" for="star-4"></label>
    <input class="rate" id="star-3" type="radio" name="rate" value="3"/>
    <label class="rate" for="star-3"></label>
    <input class="rate" id="star-2" type="radio" name="rate" value="2"/>
    <label class="rate" for="star-2"></label>
    <input class="rate" id="star-1" type="radio" name="rate" value="1"/>
    <label class="rate" for="star-1"></label>          
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您的CSS适用于之前的元素,但不适用于当前元素。

.rating label.rate:hover ~ label.rate:before,
.rating label.rate:hover:before {
    color: #FD4;
}

完整代码:

div.rating {
  display: inline-block;
}

.rating input.rate {
  display: none;
}

.rating label.rate {
  float: right;
  padding: 10px;
  font-size: 50px;
  color: #444;
}

.rating label.rate:hover~label.rate:before,
.rating label.rate:hover:before {
  color: #FD4;
}

.rating input.rate:checked~label.rate:before {
  color: #FD4;
}

label.rate:before {
  content: '*';
}
<div class="rating">
  <input class="rate" id="star-5" type="radio" name="rate" value="5" />
  <label class="rate" for="star-5"></label>
  <input class="rate" id="star-4" type="radio" name="rate" value="4" />
  <label class="rate" for="star-4"></label>
  <input class="rate" id="star-3" type="radio" name="rate" value="3" />
  <label class="rate" for="star-3"></label>
  <input class="rate" id="star-2" type="radio" name="rate" value="2" />
  <label class="rate" for="star-2"></label>
  <input class="rate" id="star-1" type="radio" name="rate" value="1" />
  <label class="rate" for="star-1"></label>
</div>