admin管理员组文章数量:1418622
I'm trying to move an element to left and right while scrolling up and down in this example FIDDLE the problem is the div will keep moving to reach out of the page and doesn't return to its original position. This is the example I'm trying to simulate Original Example
HTML
<div class='container'>
<div class='inner'>
</div>
</div>
JS
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
var offset = $(".inner").offset();
var w = $(window);
var x = offset.left;
console.log(x);
$(".inner").css("left",x+50);
} else {
var offset = $(".inner").offset();
var w = $(window);
var y = offset.left;
console.log(y);
$(".inner").css("left",y-50);
}
lastScrollTop = st;
});
CSS
.container{width:100%; position: relative; float:left; background:#fff; height:1200px;}
.inner{width:150px; height:100px; position:absolute; top:20%; left:10%; background:red;}
I'm trying to move an element to left and right while scrolling up and down in this example FIDDLE the problem is the div will keep moving to reach out of the page and doesn't return to its original position. This is the example I'm trying to simulate Original Example
HTML
<div class='container'>
<div class='inner'>
</div>
</div>
JS
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
var offset = $(".inner").offset();
var w = $(window);
var x = offset.left;
console.log(x);
$(".inner").css("left",x+50);
} else {
var offset = $(".inner").offset();
var w = $(window);
var y = offset.left;
console.log(y);
$(".inner").css("left",y-50);
}
lastScrollTop = st;
});
CSS
.container{width:100%; position: relative; float:left; background:#fff; height:1200px;}
.inner{width:150px; height:100px; position:absolute; top:20%; left:10%; background:red;}
Share
Improve this question
asked Jan 5, 2016 at 17:03
PHP UserPHP User
2,4226 gold badges52 silver badges99 bronze badges
1 Answer
Reset to default 5You need to offset it by the scrolled amount, not move it by an amount each time. You are queuing up multiple moves and adding 50px each time.
var offset = $(".inner").offset();
$(window).scroll(function(event) {
var st = $(this).scrollTop();
$(".inner").css("left", st + offset.left);
});
JSFiddle: https://jsfiddle/TrueBlueAussie/x0vtopzv/1/
Once it is locked to the scrolling, you can adjust the position using a multiplier on the st
value.
Note: JSFiddle has an 8px margin on the body
. That throws out the offset position and needs to be removed or taken into account.
https://jsfiddle/TrueBlueAussie/x0vtopzv/6/
本文标签: javascriptmove element right and left while scrolling issueStack Overflow
版权声明:本文标题:javascript - move element right and left while scrolling issue - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745292008a2651852.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论