32

I'm using the affix component in a site for a navbar and would like to disable it on smaller screens. I'm using the jquery method vs. the data and can't figure out how to turn it off when my screen resolution is smaller than 767px. I've tried capturing the window width on resize and scroll and either returning false or removing the affix classes but it doesn't really work well.

if($('#subnav').length){

    $(window).resize(function() {
        var wWidth = $(window).width();
        getSize(wWidth);
    });

    $(window).scroll(function () {
        var wWidth = $(window).width();
        getSize(wWidth);
    });

    function getSize(z){
        if(z <= 767) {
                    // I tried doing return false here, no good.
            $('#subnav').removeClass('affix').removeClass('affix-top');
            $('.nav > li').removeClass('active');
        } else {
            setNav();
        }
    }

    var wWidth = $(window).width();
    getSize(wWidth);

    function setNav (){
        $('#subnav').affix({
            offset: {
            top: 420,
            bottom: 270
            }
        });
        $('#subnav').scrollspy();
    }

}
4

2 回答 2

100

您可以像在 Bootstrap 页面上一样,仅使用 CSS 进行操作。使用@media 查询fixed来检测屏幕大小,如果屏幕低于某个大小,则不要将位置设置为。例如:

@media (min-width: 768px) {
    .affix {
        position: fixed;
    }
}

此规则仅在屏幕宽度大于 768px 时才会生效。

您也可以反之亦然,static如果屏幕小于某个尺寸,则显式设置元素的位置:

@media (max-width: 767px) {
    .affix {
        position: static;
    }
}
于 2013-06-30T21:54:57.357 回答
0

如果我错了,请纠正我,但尝试设置if(z <= 767) {if(z <= 1) {不会重新调整大小的方式?除非我错过了你的问题的重点。

于 2013-06-30T21:21:20.523 回答