如何移动div up&在窗口滚动

时间:2016-04-23 11:49:53

标签: javascript jquery

我有一个jquery函数来上下移动一些div,而在这里滚动页面是代码 - >

$(window).scroll(function() {
  $(".mydiv").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});

以上代码仅适用于一个div,例如 - >

<div class="mydiv">This div works</div>
<div class="mydiv">This div takes a high distance from above div and goes down</div>

$(window).scroll(function() {
  $(".mydiv").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});
body {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv">This div works</div>
<div class="mydiv">This div takes a high distance from above div and goes down</div>

3 个答案:

答案 0 :(得分:8)

你应该使用&#39; position:absolute&#39;和&#39; top&#39;并且&#39;离开&#39;而不是边距。 通过使用边距,您可以将它们彼此推开,从而使页面变得庞大。

$(window).scroll(function() {
  $(".mydiv").css({
    "top": ($(window).scrollTop()) + "px",
    "left": ($(window).scrollLeft()) + "px"
  });
});

请参阅此代码集 - http://codepen.io/dmoojunk/pen/JXBaXm

答案 1 :(得分:0)

编织:http://kodeweave.sourceforge.net/editor/#3bc95f551a4e9cf7c52418361b4be806

这是一个简单的解决方案。用.mydiv替换#scroll

虽然你可以在CSS中做到这一点。所以我不明白你为什么需要JS。

&#13;
&#13;
$(window).scroll(function() {
  $("#scroll").css({
    "margin-top": ($(window).scrollTop()) + "px",
    "margin-left": ($(window).scrollLeft()) + "px"
  });
});
&#13;
body {
  height: 1176px;
  padding: 1em;
  font-size: 13px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv" id="scroll">This div works</div>
<div class="mydiv" id="scroll">This div takes a high distance from above div and goes down</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是一个简单的解决方案,只需添加此js

(function() {
var delay = false;

$(document).on('mousewheel DOMMouseScroll', function(event) {
    // event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},100)

    var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

    var a= document.getElementsByClassName('mydiv');
    if(wd < 0) {
        for(var i = 0 ; i < a.length ; i++) {
            var t = a[i].getClientRects()[0].top;
            
            if(t >= 40) break;
            
        }
    }
    else {
        for(var i = a.length-1 ; i >= 0 ; i--) {
            var t = a[i].getClientRects()[0].top;
             
            if(t < -20) break;
            
        }
    }
    if(i >= 0 && i < a.length) {
        $('html,body').animate({
            scrollTop: a[i].offsetTop
        });

    }
});
})();
.fake-container{height: 100vh;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv" id="scroll">scroll 1</div>
<div class="mydiv" id="scroll">scroll 2</div>