簡體   English   中英

如何在斷點處禁用JavaScript,如媒體查詢

[英]How to disable JavaScript at breakpoint like a media query

我有受JavaScript影響的<header><nav>塊。 如果窗口小於或等於1200px寬,如何創建與媒體查詢等效的JavaScript以禁用所有此JavaScript代碼?

我當前的JavaScript,沒有停止運行的指令( </html>之前的最后一件事):

<script>
    $(window).scroll(function() {
        if ($(this).scrollTop()>119)
         {
            $('header').fadeOut();
            $('nav').css({position: 'fixed', top: '0px'});
         }
        else
         {
          $('header').fadeIn();
          $('nav').css({position: 'absolute', top: 'auto'});
         }
    });
</script>


我試過包裝代碼

if (document.documentElement.clientWidth <= 1200) {
    // scripts
}

if (screen.width <= 1200) {
    // scripts
}

沒有運氣。

包裝代碼是正確的方法。 由於你已經在使用jQuery,你可以這樣做

if($(window).width() > 1200) {
  // the rest of your code goes here
}

請注意,我使用的是>而不是<= ,因為如果它大於1200px則要運行它,並且如果它小於或等於1200px,則希望忽略它。

在您的代碼中嘗試此操作:

<script>
    var windowWidth = $(window).width();

    if(windowWidth >= 1200)
    {
        $(window).scroll(function() {
            if ($(this).scrollTop()>119)
            {
                $('header').fadeOut();
                $('nav').css({position: 'fixed', top: '0px'});
            }
            else
            {
                $('header').fadeIn();
                $('nav').css({position: 'absolute', top: 'auto'});
            }
        });
    }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM