使可折叠标题正确自适应

时间:2015-07-20 19:11:59

标签: javascript jquery html css

我尝试使用可折叠标头制作自适应网站。标题必须在文档宽度超过992px时折叠,并且必须固定在小于992的宽度上。

问题是:当我们将窗口从大到小调整大小时,崩溃的能力不会像预期的那样消失。但是当我们从小窗口宽度调整到大窗口宽度时,它会起作用。

我使用了简单的jquery代码:

$(function() {

    var width = $(document).width();

    $(window).on("orientationchange load resize", function() {
        width = $(document).width();
        if (width > 992) {
            $(window).scroll(function() {
                var header = $('header');

                if ($(this).scrollTop() > 50) {

                    header.addClass('collapse');

                } else {

                    header.removeClass('collapse');
                }
            });
        }
    });

请看小提琴:http://jsfiddle.net/19fmc8wa/2/

感谢。

1 个答案:

答案 0 :(得分:1)

你走了,你几乎拥有它。如果我完全没有使用该功能,请告诉我,但我尽量保持与您的原始代码类似。

  $(function(){

    function collapse(subj, removalBool){
        if (subj && !removalBool){
            $(subj).removeClass('collapse');
        }
        else {
            $(subj).addClass('collapse');
        }        
    }

    function changePos(){
        var pos = { 
            "fixed": 992
        };
    }


    $(window).on('scroll', function(){
        if ($(window).scrollTop() > 50 &&  $(document).width() > 992 ){
            collapse('header', true);

        }
        else {
            collapse('header');
        }
    });

});

调整大小事件不需要像你一样嵌套,尽管我看到你在想什么。相反,只要滚动事件触发,就会使用JavaScript来读取文档的宽度,而不是在重新调整大小事件时触发。

然后我使用CSS媒体查询来控制固定位置,具体取决于屏幕宽度:

header {
    background-color: red;
    height: 200px;
    transition: height .3s;
    width: 100%;
    top: 0;
    left: 0;

}
main {
    background-color: #abc;
    height: 700px;
}
.collapse {
    background: yellow !important;
    height: 50px;
    transition: height .3s;
}

@media all and (min-width: 992px) {
      header {
      position: relative;
        background: blue;
    }   
}

@media all and (max-width: 992px) {
 header {
      position: fixed;
    }   
}

希望这有帮助!

<强>已更新 http://jsfiddle.net/19fmc8wa/6/