最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - move element right and left while scrolling issue - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

You 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/

发布评论

评论列表(0)

  1. 暂无评论