使可折叠页眉正确自适应

Make collapsible header correctly adaptive

本文关键字:自适应 可折叠      更新时间:2023-09-26

我尝试制作一个具有可折叠页眉的自适应站点。页眉必须在文档宽度大于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/

谢谢。

给你,你差一点就成功了。让我知道,如果我关闭的功能,但我试图保持类似于你的原始代码尽可能。

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

Resize事件不需要像你那样嵌套,尽管我知道你在想什么。相反,当scroll事件触发时,使用JavaScript读取文档的宽度,而不是当resize事件触发时。

然后我使用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/