Animate continuously onMouseover using setInterval

橙三吉。 提交于 2021-01-29 05:52:41

问题


I have been stuck with this problem for quite some time now and i have searched on Google for countless hours to come up with a solution but to no avail.

Here is my Problem

I want to know the Logic behind a Carousel and would like to make it slide from right to left or vice-versa when a user hovers on the respective buttons.

How can i make it animate continuously on mouseenter?

Any help would be deeply appreciated. Thank You :)

Here is the JSFIDDLE: http://jsfiddle.net/neoragex/qXseV/


回答1:


I have updated your version, check it out :) http://jsfiddle.net/qXseV/2/

What I did is add the following to your css of the .mid class:

position:absolute;
top:20px;

And I changed your setInterval to:

timer = setInterval(function() {slide();}, 400);

EDIT: extra jsfiddle with both left and right movement http://jsfiddle.net/qXseV/7/




回答2:


I made some adjustments at your timer implementation and fixed the missing css position:relative on the element to be slided, since you are manipulating the left value, that in turn can only be used if the element has a position.

HTML

<div id="leftarrow">HOVER</div>
<div class="mid"></div>

CSS

.mid {
    clear: both;
    border: 1px solid black;
    background-color: green;
    width: 100px;
    height: 100px;    
    position: relative;
}
#leftarrow {
    float: left;
    border: 1px solid black;
    margin-bottom: 4px;
    cursor: pointer;
}

JQUERY

// declare variables
var timer;
var speed = 400;

// slide function
function slide() {
    return setInterval(function() {
        $(".mid").animate({
            'left': '+=20px'
        }, 200);
    }, speed);
}

// hover event for the button
$("#leftarrow").hover(function() {
    timer = slide();
}, function() {
    clearInterval(timer);
});

See the Fiddle Here!



来源:https://stackoverflow.com/questions/10512835/animate-continuously-onmouseover-using-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!