固定边栏直到div [英] fixed sidebar until a div

查看:106
本文介绍了固定边栏直到div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用此代码:

I'm currently using this code:

$(document).ready(function () {  
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();

        // whether that's below the form
        if (y >= top) {
            // if so, ad the fixed class
            $('#sidebar').addClass('fixed');
        } else {
            // otherwise remove it
            $('#sidebar').removeClass('fixed');
        }
    });
});

它设置固定在特定点后向下滚动。我想让我的侧栏停止固定后到达一点,这可能是从整个页面的底部200px。

It sets fixed on my sidebar when I scroll down after a specific point. I want that my sidebar stops being fixed after it reaches a point, which could be 200px from the bottom of the whole page. How can I do this?

推荐答案

您只需在事件处理程序中添加更多检查和计算。这里是一些修改后的代码,应该做你想要的:

You just need to add a few more checks and calculations in your event handler. Here's some revised code that should do what you want:

$(function() {
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    var footTop = $('#background2').offset().top - parseFloat($('#background2').css('marginTop').replace(/auto/, 0));
    var maxY = footTop - $('#sidebar').outerHeight();
    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        if (y > top) {
            if (y < maxY) {
                $('#sidebar').addClass('fixed').removeAttr('style');
            } else {
                $('#sidebar').removeClass('fixed').css({
                    position: 'absolute',
                    top: (maxY - top) + 'px'
                });
            }
        } else {
            $('#sidebar').removeClass('fixed');
        }
    });
});

您可以看到它有效在这个jsFiddle

这篇关于固定边栏直到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆