问题
I would know how to make my rating star always hover depending on the average rating result (random generated number from 1-5 and random generated number from 10-55 for the number of votes)? Can I simulate hover with jQuery on my star? I saw few solutions to similar problems but none used in their css the General Sibling Selector (~).
The star hover funcionality must be in pure css. Everything other can be and is in js(jQuery). When the document loads some stars should already be hovering(depeding on the random average number), and when the user clicks on the star the new value should also affect the hovering stars.
Here is a js fiddle illustrating my problem: http://jsfiddle.net/kingSlayer/8ZbxB/
CSS
div.rating-star{
display:inline-block;
width:30px;
height:30px;
background-image: url(star.png);
background-size: contain;
background-repeat: no-repeat;
}
div:hover div.rating-star {
background-image: url(star-hover.png);
background-size: contain;
background-repeat: no-repeat;
}
div.rating-star:hover ~ div.rating-star {
background-image: url(star.png);
background-size: contain;
background-repeat: no-repeat;
}
HTML
<div id="showRating"></div>
<div class="rate_stars">
<div id="one" class='rating-star' onclick="rating(1);"></div>
<div id="two" class='rating-star' onclick="rating(2);"></div>
<div id="three" class='rating-star' onclick="rating(3);"></div>
<div id="four" class='rating-star' onclick="rating(4);"></div>
<div id="five" class='rating-star' onclick="rating(5);"></div>
</div>
JavaScript
var averageRate = (Math.random() * 4) + 1;
$('#showRating').text('Average rating: ' + averageRate.toFixed(1));
var numberOfRates = Math.floor((Math.random() * 55) + 1);
function rating(rate) {
var result = ((averageRate * numberOfRates) + rate) / (numberOfRates + 1);
$('#showRating').text('Average rating: ' + result.toFixed(1));
}
if (result <= 1.4) {
}
if (result > 1.4 && result <= 2.4) {
}
if (result > 2.4 && result <= 3.4) {
}
if (result > 3 && result <= 4.4) {
}
if (result > 4.4) {
}
回答1:
The easiest way would be to use JavaScript to detect the hover, and on hover in/out add/remove a "hover" or "active" class. CSS can then use .rating-star.hover
or similar instead of :hover
. This way you can use JavaScript to just apply the class of your choice to the apt number of stars when none of them are being hovered over.
Clear as mud?
来源:https://stackoverflow.com/questions/17883353/simulate-hover-rating-stars-made-with-selectors-in-css