javascript - 阻止 DIV 越过指定位置

标签 javascript jquery html css scroll

我需要阻止 #first#second div 越过绿线。该示例将向您解释一切。

http://jsfiddle.net/3QdJt/1/

当我向上滚动时效果很好,但当我向下滚动时,DIV 会跳动。

HTML

<div id="first"></div>
<div id="second"></div>
<div id="donotcross"></div>

CSS

#donotcross {
    position: relative;
    width 500px;
    height: 5px;
    top: 487px;
    background: green;
}

#first {
    position: fixed;
    width: 50px;
    height: 50px;
    background: red;
    right: 20px;
    bottom: 50%;
    margin-bottom: 50px;
}

#second {
    position: fixed;
    width: 50px;
    height: 50px;
    background: yellow;
    right: 20px;
    bottom: 50%;
    margin-bottom: -50px;
}

jQuery

$(window).scroll(function () {
    windowPos = $(this).scrollTop();
    asd = $('#first').offset().top;
    tauto = 500 - windowPos;
     if(asd <= 500) { 
       $('#first').css('top', tauto);
       $('#second').css('top', 600 - windowPos);
   } 
   if (asd > 500 ){
       $('#first').css('top', 'auto');
       $('#second').css('top', 'auto');
   }
});

最佳答案

您需要检查 windowPos 变量而不是检查 asd > 500。跳跃是由于您将箱子移动到超过 500 个而引起的。因此,为了避免跳跃,您可能需要这样做

$(window).scroll(function () {
    windowPos = $(this).scrollTop();
    asd = $('#first').offset().top;
    tauto = 500 - windowPos;
     if(asd <= 500) { 
       $('#first').css('top', tauto);
       $('#second').css('top', 600 - windowPos);
   } 
   if (windowPos > 500 ){
       $('#first').css('top', 'auto');
       $('#second').css('top', 'auto');
   }
});

编辑:

为了达到粘性效果,我手动计算了盒子的位置,而不是使用 top:auto

    $(window).scroll(function () {

    var center = $(window).height() / 2;
    //the 50 is the the #first and #second offset diff divide by 2
    var firstBoxTop = center - 50;
    var secondBoxTop = center + 50;

    var windowPos = $(this).scrollTop();
    if((windowPos + firstBoxTop) < 500)  { 
        firstBoxTop = 500 - windowPos; 
    }
    if((windowPos + secondBoxTop) < 600) { 
        secondBoxTop = 600 - windowPos; 
    }
    $('#first').css('top', firstBoxTop);
    $('#second').css('top', secondBoxTop);
});

关于javascript - 阻止 DIV 越过指定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23077480/

相关文章:

javascript - 简单的 JQuery 滑动效果不同步

jQuery 后面有随机数?

html - 有没有办法让元素在不从流中移除的情况下被定位到右边?

javascript - 当您返回浏览器时如何避免重新计算值(value)?

javascript - 如何让复选框函数访问 Angularjs 中的表数据

javascript - jqGrid - 网格初始化事件

html - 使用 css 控制 svg 的大小和颜色

html - 3 列布局,如果太窄,最右边的列会在中间一列下方环绕

javascript - 更改 jQuery UI Datepicker 的位置

javascript - d3v4 为什么我的线条元素没有出现?