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

Javascript 如何使用.offset.top结束固定元素,javascript,jquery,html,css,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();

我正在使用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>

$(文档).ready(函数(){
var sidebartop=$('.single content').offset().top;
$(窗口)。滚动(功能(事件){
var y=$(this.scrollTop();
如果(y>=sidebartop){
$(“#共享链接”).addClass('fixed');
}否则{
$(“#共享链接”).removeClass('fixed');
}
});
});
这是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插件来解决这个问题

演示:

插件和源代码

用法: 编辑: 如果你只是在寻找那一行,你应该用它来计算
.single content
top

$(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');
        }
    });
});

将您的html和css代码共享为well@TomSarduy完成我添加了它我不太擅长javascript。我只需要固定div结束的那一行,因为var非常合理,但是你也能提供这个函数吗
$(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');
        }
    });
});