javascript - 如何使用 .offset.top 结束固定元素

标签 javascript jquery html css

我正在使用 Javascript 代码 .offset.top 来修复一个元素,但我想在到达另一个元素时结束它。

<script>
    $(document).ready(function (){
        var sidebartop = $('.single-content').offset().top;
        $(window).scroll(function (event){
            var y = $(this).scrollTop();
            if ( y>= sidebartop ){
                $('#sharing-links').addClass('fixed');
            } else {
                $('#sharing-links').removeClass('fixed');
            }
        });
    });
</script>

这是html

    <div id="sharing-links">
    <!-- this is the fixed element -->
</div>
<div class="single-content">
    <!-- when the div reaches here is adds the .fixed -->
    <div class="div2">
        <!-- I want the fixed element to end when it reaches this div -->
    </div>
</div>

有人知道怎么解决吗?

最佳答案

有很多关于这个主题的相关问题,你会发现很多技巧,有些有效,有些不太好,但是当滚动固定时,我总是使用这个 jquery 插件,旨在解决这个确切的问题。

演示:

http://jsfiddle.net/ZczEt/167/ http://jsfiddle.net/y3qV5/434/ http://jsfiddle.net/k2R3G/81/

插件和源代码

https://github.com/bigspotteddog/ScrollToFixed

用法:

$(document).ready(function() {
  $('#mydiv').scrollToFixed();
});

编辑:

如果您只是在寻找那一行,您应该使用它来计算 .single-content 顶部。

$(document).ready(function (){
    var auxtop = $('.single-content').offset().top 
    var margintop = parseFloat($('.single-content').css('margin-top').replace(/auto/, 0));
    var sidebartop = auxtop - margintop;
    $(window).scroll(function (event){
        var y = $(this).scrollTop();
        if ( y>= sidebartop ){
            $('#sharing-links').addClass('fixed');
        } else {
            $('#sharing-links').removeClass('fixed');
        }
    });
});

关于javascript - 如何使用 .offset.top 结束固定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872216/

相关文章:

javascript - 为什么 videojs 按空格键切换全屏,而不是切换播放/暂停

javascript - 我可以在 Node 的 q Promise 中创建全局变量吗?

javascript - Google Apps 脚本中的数组 "includes"方法失败

jquery-ui - 防止JQuery的恶意覆盖

asp.net - 检测所有 HTML 页面渲染何时发生

html - <li> 元素对齐 - 减少元素符号左侧的空间

Javascript 搜索引擎(搜索自己的站点)

javascript - 在js中重置单选按钮和复选框值

jQuery移动按钮默认旋转90°并添加到网格

html - 我怎样才能让一个图像作为一个按钮,并让它在点击时执行一个 Action (启动一个关键帧事件,运行一个脚本)?