jQuery 当用户滚动时移动图像或元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21238753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move an image or element when user scrolls
提问by Esser
I'm trying to figure out how to move an image on the scroll event. I used .animate
, but that moves it all the way, even after the user lets go. I want it to stop when the user stops scrolling.
我想弄清楚如何在滚动事件上移动图像。我使用了.animate
,但它一直在移动,即使在用户放手之后也是如此。我希望它在用户停止滚动时停止。
采纳答案by Craighead
Stack:Determine the direction of scroll
By using this, you can then use .animate
通过使用它,您可以使用 .animate
var lastScrollTop = 0;
$("div").scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('img').animate({top: '-=10'}, 10);
} else {
$('img').animate({top: '+=10'}, 10);
}
lastScrollTop = st;
});
Disregard:If you would like the image to move with the page, add position: fixed;
to the CSS.
忽略:如果您希望图像随页面移动,请添加position: fixed;
到 CSS。
回答by Arno
You could use
你可以用
$(window).scroll(function() { $(image).position($(image).position().top + 10); });
$(window).scroll(function() { $(image).position($(image).position().top + 10); });
depending on your CSS. If you could provide some code (in a jsFiddle), maybe I would be able to help you a bit better.
取决于你的 CSS。如果您可以提供一些代码(在 jsFiddle 中),也许我可以更好地帮助您。