Javascript“悬停时”环形
任何人都可以帮助我解决这个问题...我有一个按钮,当悬停时会触发一个操作。但我希望只要按钮悬停就重复它。
我很感激任何解决方案,无论是在 jquery 还是纯 javascript 中 - 这是我的代码此时的样子(在 jquery 中):
var scrollingposition = 0;
$('#button').hover(function(){
++scrollingposition;
$('#object').css("right", scrollingposition);
});
现在我如何将其放入某种 while 循环中,以便 #object 将 px 移动px for #button 悬停,而不只是当鼠标进入时?
Can anybody help me on this one...I have a button which when is hovered, triggers an action. But I'd like it to repeat it for as long as the button is hovered.
I'd appreciate any solution, be it in jquery or pure javascript - here is how my code looks at this moment (in jquery):
var scrollingposition = 0;
$('#button').hover(function(){
++scrollingposition;
$('#object').css("right", scrollingposition);
});
Now how can i put this into some kind of while loop, so that #object is moving px by px for as #button is hovered, not just when the mouse enters it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好的...另一个答案:
250
表示任务每四分之一秒重复一次。您可以减少此数字以使其更快,或增加此数字以使其更慢。OK... another stab at the answer:
The
250
means the task repeats every quarter of a second. You can decrease this number to make it faster or increase it to make it slower.内森的回答是一个好的开始,但是您还应该使用< a href="https://developer.mozilla.org/en-US/docs/DOM/window.clearInterval" rel="nofollow noreferrer">window.clearInterval 当鼠标离开元素时(mouseleave 事件)取消使用 setInterval(),因为这样“循环”仅在鼠标指针进入时运行元素(mouseover 事件)。
这是一个示例代码:
我在 jsFiddle 上创建了一个示例代码,它演示了如何使用上面显示的代码从左向右滚动元素的背景图像,然后在
hover
上向后滚动:http://jsfiddle.net/Sk8erPeter/HLT3J/15/
Nathan's answer is a good start, but you should also use window.clearInterval when the mouse leaves the element (mouseleave event) to cancel the repeated action which was set up using setInterval(), because this way the "loop" is running only when the mouse pointer enters the element (mouseover event).
Here is a sample code:
I created a sample code on jsFiddle which demonstrates how to scroll the background-image of an element left-to-right and then backwards on
hover
with the code shown above:http://jsfiddle.net/Sk8erPeter/HLT3J/15/
如果是动画,您可以在动画进行到一半时“停止”。所以看起来你正在向左移动一些东西,这样你就可以这样做:
If its an animation you can "stop" an animation half way through. So it looks like you're moving something to the left so you could do:
如果您想对多个对象执行此操作,那么最好使其比全局变量更加面向对象。
编辑:
认为处理多个对象的最佳方法是将其放入 .each() 块中:
Edit2:
或者你可以通过添加一个类来做到这一点:
If you want to do this for multiple objects, it might be better to make it a bit more object oriented than a global variable though.
Edit:
Think the best way of dealing with multiple objects is to put it in an .each() block:
Edit2:
Or you could do it by adding a class: