为什么在页面刷新时显示隐藏元素起作用

Why display hide elements work when page refresh

我写了一个 jQuery 来在页面调整大小时(针对移动设备)隐藏内容中的 div。它第一次运行良好,但当我重新加载页面时,它显示隐藏元素(我隐藏在 jQuery)。

这是我的 jQuery 代码:

$(window).resize(function () {    
    if ($(this).width() < 1200) {
        $('.divHide').hide(); 
    } else {
        $('.divHide').show();
    }    
});

你必须准备好在文档中编写函数。

$( document ).ready(function() {
     if ($(this).width() < 1200) {
             $('.divHide').hide();
          }
          else {
             $('.divHide').show();
          }
});

更好的方法是

 function myfunction() {
       if ($(this).width() < 1200) {
         $('.divHide').hide();
      }
      else {
         $('.divHide').show();
      }
    }
 $(document).ready(myfunction);
 $(window).on('resize',myfunction);