调试滞后计算余量顶部位置固定侧边栏滚动到底部

时间:2015-05-04 09:58:24

标签: javascript jquery performance twitter-bootstrap-3 css-position

我想在响应式视图中修复左侧边栏。

我使用边距顶部(滚动位置的依赖性)作为侧边栏的包装! 那是工作!但在某些浏览器上它是慢动作(例如:macbook pro retina 15“2014 chrome version 42)

jsfiddle

 jQuery(function($){
    var target = $('#fixed_sidebar .fixed');
    var sidebarPosition = $(target).offset().top;

    function calculatesidebar(){
        var  heightWindow = $(window).height();
        var scrollPosition = $(document).scrollTop();
        var sidebarHeight = target.outerHeight();
        var positionOftarget = (sidebarPosition + sidebarHeight) - heightWindow;
        var targetMargin =  parseInt(target.css('marginTop'));


        if (scrollPosition >= positionOftarget){
            var margin = scrollPosition - positionOftarget;
            target.css('marginTop', margin+'px');

        }else{
            target.css('marginTop', '0');
        }

    }

    $( window ).scroll(function(){
        calculatesidebar();
    });
    $( window ).resize(function() {
        calculatesidebar();
    });

});

1 个答案:

答案 0 :(得分:2)

我以其他方式解决了

jsfiddle

jQuery(function ($) {


    function fixed_sidebar_bottom(wrapper, target) {
        var left = $(wrapper).offset().left,
            right = $(wrapper).offset().right,
            top = $(wrapper).offset().top,
            width = $(wrapper).width(),
            target = $(target),
            targetHeight = target.outerHeight(),
            scrollPosition = $(document).scrollTop(),
            windowHeight = $(window).height(),
            windowWidth = $(window).width(),
            hotSpot = (top + targetHeight) - windowHeight;


            if (scrollPosition >= hotSpot) {

                if (!target.attr('style')) {
                    target.css({'left': left, 'right': right, 'position': 'fixed', 'bottom': '0', 'width': width});
                } else {
                    target.css({'left': left, 'right': right, 'width': width});
                }
            } else {
                target.removeAttr("style");
            }
        }





    $(window).scroll(function () {
        fixed_sidebar_bottom('#fixed_sidebarLeft','#fixed_sidebarLeft_target');    
    });

    $(window).resize(function () {
        fixed_sidebar_bottom('#fixed_sidebarLeft','#fixed_sidebarLeft_target'); 
    });
});