I have written a script. It does work! It's just a bit rubbish. Could someone tell me where I am going wrong.
Basically, I have a 5 star rating box. When the mouse hovers over the various parts of the box I need the stars to change.
Currently the stars only change when you move your mouse over and out of the element. I need the stars to change while the mouses within the element. I think the problem is with the event but I have tried a couple and it seems to make no difference.
$(".rating").mouseover(function(e) {
// Get Element Position
var position = $(this).position();
var left = position.left;
// Get mouse position
var mouseLeft = e.pageX;
// Get Actual
var actLeft = mouseLeft - left;
$(".info").html(actLeft);
if (actLeft < 20) {
$(this).attr('style', 'background-position:0;');
} else if (actLeft < 40) {
$(this).attr('style', 'background-position:0 -20px;');
} else if (actLeft < 60) {
$(this).attr('style', 'background-position:0 -40px;');
} else if (actLeft < 80) {
$(this).attr('style', 'background-position:0 -60px;');
} else {
$(this).attr('style', 'background-position:0 -80px;');
}
});
I know it's pretty funky but I'd figure I put it here to get feedbacks ^^. I haven't tested it, but it should work.
This being said, how about using pure CSS to do that:
<div class="stars">
<span>Star<span>Star<span>Star<span>Star</span></span></span></span>
</div>
.stars span{
background: url(not-selected.png);
}
.stars span:hover{
background:url(selected.png);
}
Try this code:
jQuery:
<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(function() {
$.each($('.starHighlight div'), function(i, val) {
$(val)
.hover(function() {
//TODO: remove hard coded numbers and calculate it based on icon size/number of stars
var starShift = (4 - i) * -20;
$(val).parent().css("backgroundPosition", starShift + "px bottom");
}, function() {
$(val).parent().css("backgroundPosition", "0 0");
});
});
});
/* ]]> */
</script>
CSS:
<style type="text/css">
.starSelector, .starHighlight { width:100px !important; height:20px; background:url(http://front-end-developer.net/examples/star.png) top no-repeat; }
.starSelector div { cursor:pointer; width:20px; height:20px; float:left; text-indent:-1000px; }
.starHighlight { background-position:-100px bottom; }
</style>
XHTML:
<div class="starSelector">
<div class="starHighlight">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div>
</div>
</div>
Edit: Tested on Firefox, Chrome, IE6, IE7 and IE8.
You probably have to add some sort of click event to keep the number of highlighted stars up when user mouse-out of the control.
The mouseover event is triggered when the mouse enters an element. The event you want is mousemove .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.