jQuery悬停以无限循环改变各种背景,直到鼠标移出
我有一个带有背景图像的
,它将更改背景 4 次,延迟 300 毫秒。我尝试过使用 setTimeout ,它似乎工作正常,但是clearTimeout(t);当鼠标移出时由于背景继续变化而失败。$(document).ready(function() {
$(".image").hover(function(){
var obj = $('.image');
$(this).css("background-position", "0 -90");
var t=setTimeout(function(){obj.css("background-position", "0 -180")}, 300);
var t=setTimeout(function(){obj.css("background-position", "0 -270")}, 600);
var t=setTimeout(function(){obj.css("background-position", "0 -360")}, 900);
}, function() {
$(this).css("background-position", "0 0");
clearTimeout(t);
});
});
我也想在悬停函数中插入一种无限循环的方法,直到释放鼠标。
对不起我的学校英语。
提前致谢!
I've a <div>
with a background-image that will change the background 4 times with a delay of 300ms. I've tried with setTimeout which seems to work correct, but clearTimeout(t); when the mouse moves out fails because the backgrounds continue changing.
$(document).ready(function() {
$(".image").hover(function(){
var obj = $('.image');
$(this).css("background-position", "0 -90");
var t=setTimeout(function(){obj.css("background-position", "0 -180")}, 300);
var t=setTimeout(function(){obj.css("background-position", "0 -270")}, 600);
var t=setTimeout(function(){obj.css("background-position", "0 -360")}, 900);
}, function() {
$(this).css("background-position", "0 0");
clearTimeout(t);
});
});
I would like too to insert to the hover function a way to have a infinite loop until the mouse is released.
Sorry for my school English.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 t var dec 移到函数之外。那么它就会在闭包中。
例如这样的:
这段代码还有其他问题,但我只是回答这个问题。
move the t var dec outside of the function. then it will be in the closure.
eg something like this:
There are other issues with this code but I'm just answering the question.
因为这样变量
t
会被前两个setTimeout
覆盖两次,所以只保留最后一个setTimeout
的代码,所以当您调用clearTimeout
仅清除最后一个setTimeout
。您可以做的是使用三个不同的变量来存储它,改为
setInterval
,或者使用循环来设置超时。Because with this the variable
t
is overwritten twice by the two previoussetTimeout
s, so only the code for the lastsetTimeout
is preserved, so when you callclearTimeout
you're only clearing the lastsetTimeout
.What you can do is to use three different variables to store this, change to
setInterval
instead, or use a loop to set the timeouts.你试过jquery的animate吗?可能会简化很多事情——他们会为你处理所有的计时器和东西。它已融入您已经使用的库中,所以为什么不利用它呢?
默认情况下,它将使用线性动画,但您可以设置不同的缓动,如果您想要一些不同的东西。
Have you tried jquery's animate? Would probably simplify things a lot -- they'll deal with all the timers and stuff for you. It's baked into the library you're already using so why not take advantage of it?
By default it's going to use a liniar animation, but you could set up different easing if you wanted something different.