只在宽度以下和宽度以上各准备一次

Only prepend one time below a width and one time above a width

本文关键字:一次      更新时间:2023-09-26

无论我在两种大小之间切换多少次,当浏览器大小低于768px时,我都希望在网页中预先添加一个页眉标记,当浏览器尺寸高于768px后,将其删除。我创建了下面的代码,如果我使用大小调整窗口,它可以很好地工作,但如果我手动调整它的大小,它就会不断地激发,导致多个标题标记。

我希望它只在低于768px和高于768px的情况下发射一次。

起初,我的代码没有包含在resize函数中,但后来它只工作一次,所以如果我将其增加到768px左右,header标记就会消失,但如果我再次减小大小,header就不会被重新应用。

$(document).ready(function (){
    $(window).on('resize', function(){
        var width = $(window).width();
        if (width < 768) {
            insertHeader();
        }
        if(width > 767) {
            removeHeader();
        }
    });
});
//Function to add header
function insertHeader() {
    var headerTag = $("body").prepend(
                    "<header class='container container-style'> '
                        <div class='row'> '
                            <div class='col-xs-12'> '
                                <a href='#'><img class='img-responsive'  '
                                    src='img/dreamstime_s_52258696.jpg' alt='cartoon drawing of 1965 GTO'></a> '
                            </div>  '
                        </div> '
                    </header>");
    return headerTag
}
function removeHeader() {
    var headerTag = $("header").remove();
    return headerTag;   
}

您可以使用css媒体查询

@media (max-width: 768px) {
  .container {
    display: none;
  }
}

plnkrhttp://plnkr.co/edit/BsL71H91RVFgG3gUDexa?p=preview

您只想取消对事件的影响,有很多方法可以做到这一点,但在这种情况下,一个简单的标志就足够了

$(window).data('flag', $(window).width() < 768).on('resize', function() {
    var width = $(window).width();
    var flag  = $(this).data('flag');
    if (width < 768 && flag) {
        insertHeader();
        $(this).data('flag', false);
    } else if (width > 768 && !flag) {
        removeHeader();
        $(this).data('flag', true);
    }
});

FIDDLE

检查标头是否在DOM中

if($('header').length < 1){
}

你的代码应该看起来像

$(document).ready(function (){
    $(window).on('resize', function(){
        var width = $(window).width();
        if (width < 768) {
          if($('header').length < 1){
             insertHeader();
          }
        }
        if(width > 767) {
           if($('header').length >= 1){
             removeHeader();
           }
        }
    });
});

演示此处