jQuery and executing code until mouseout is called
Good day all, I am tasked with building a slider for our site. Here is my goal:
<div id="abc">
<div id="slider">...</div>
</div>
I need to move "slider" left 30px at a time when a button is hovered over, and right 30px when another button is hovered over.
My problem is that there doesn't seem to be a reliable method for telling the code that the mouse hasn't left the are in question, unless there is something I did not think about or read yet. In other words, when the mouse is OVER the a button, the code to move "slider" left is executed until the mouseout is called. I'm not really sure how to do this.
The only way I can think of is to look at the offsetTop and offsetLeft and offsetTop DO开发者_开发问答M properties and compare them to the mouse position, than run checks to see if the mouse is within the bounds of the box, and if not than it will stop the execution of code.
Is there a better way to do this?
This is fairly easy.
var timerID;
$("#left").hover(function() {
timerID = setInterval(slideLeft, 1000);
}, function() {
clearInterval(timerID);
});
function slideLeft() {
$("#slider").animate({left: -30});
}
and similar for right.
You only need to use hover()
if there's something you need to stop when the mouse leaves the area. Otherwise you can simply use the mouseover()
event.
Note: the actual effect I've put in there probably isn't right but it depends entirely on the slider plugin you're using. Adjust as required.
You don't have to check where the mouse is, as the mouseout
event will be triggered when the mouse leaves the element.
To make the movement repeat while the mouse is hovering the element, start an interval that you stop when the mouse leaves the element:
$(function(){
var moveInterval;
$('#moveLeft').hover(function(){
moveInterval = window.setInterval(function(){
// here you move the slider
}, 100);
}, function(){
window.clearInterval(moveInterval);
});
});
精彩评论