我正在制定评级系统。我必须突出所有的星星,直到星星徘徊。 我的dom是这样的:
<div class="star">
<i class="fa rating-star" ></i><!--
--><i class="fa rating-star" ></i>
<i class="fa rating-star" ></i><!--
--><i class="fa rating-star" ></i>
<i class="fa rating-star" ></i><!--
--><i class="fa rating-star" ></i>
<i class="fa rating-star" ></i><!--
--><i class="fa rating-star" ></i>
<i class="fa rating-star" ></i><!--
--><i class="fa rating-star" ></i>
</div>
现在假设一个人徘徊在8号星上,所以我必须突出所有的星星,直到第八颗星。 使用这个css:
.rating-star{
cursor: pointer;
}
.rating-star:hover{
color: #ffcc00;
}
使用这个js,但我得到的最大调用堆栈大小超出错误。
$(document).ready(function() {
var halfStarArray = $('.star i');
$('.star i').mouseover(function() {
var index = $(this).index();
for (var i = 0; i <= index; i++) {
$(halfStarArray[i]).trigger('mouseenter');
}
});
});
答案 0 :(得分:1)
试试这个:你已经绑定了鼠标悬停事件并明确地触发了mouseenter事件,这会调用你的绑定事件并进入无限循环。
您可以在hover
事件中添加和删除前面的元素。
$(document).ready(function() {
var halfStarArray = $('.star i');
$('.star i').hover(function() {
var index = $(this).index();
//add class to all previous li elements using `lt` selector
$('.star i:lt(' + index + ')').addClass('rating-star-hover');
$(this).addClass('rating-star-hover');
}, function() {
var index = $(this).index();
//remove class from all previous li elements using `lt` selector
$('.star i:lt(' + index + ')').removeClass('rating-star-hover');
$(this).removeClass('rating-star-hover');
});
});
&#13;
.rating-star{
cursor: pointer;
}
.rating-star-hover{
color: #ffcc00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="star">
<i class="fa rating-star" >11</i><i class="fa rating-star" > 22 </i>
<i class="fa rating-star" >12</i><i class="fa rating-star" > 33 </i>
<i class="fa rating-star" >13</i><i class="fa rating-star" > 44 </i>
<i class="fa rating-star" >14</i><i class="fa rating-star" > 55 </i>
<i class="fa rating-star" >15</i><i class="fa rating-star" > 66 </i>
</div>
&#13;
答案 1 :(得分:1)
试试这个:
.rating-star {
cursor: pointer;
}
.rating-star-hover {
color: #ffcc00;
}
<div class="star">
<i class="fa rating-star">0</i>
<i class="fa rating-star">1</i>
<i class="fa rating-star">2</i>
<i class="fa rating-star">3</i>
<i class="fa rating-star">4</i>
<i class="fa rating-star">5</i>
<i class="fa rating-star">6</i>
<i class="fa rating-star">7</i>
<i class="fa rating-star">8</i>
<i class="fa rating-star">9</i>
</div>
<script>
$(document).ready(function () {
var halfStarArray = $('.star i');
$('.star i').mouseover(function () {
var found = false;
for (var i = 0; i <= halfStarArray.length; i++) {
if (found)
break;
else {
$(halfStarArray[i]).addClass('rating-star-hover');
if (halfStarArray[i] === this)
found = true;
}
}
});
$('.star i').mouseout(function () {
halfStarArray.removeClass('rating-star-hover');
});
});
</script>