在 window 调整大小时隐藏元素

Hide element on window resize

我试图构建一个 table,它会在 window 达到一定大小时出现。现在,我想通过在 window 达到一定大小时隐藏 table 来提高响应速度。我看过 window.onresize(),但我不确定如何使用以下代码实现它。

 if (iedom||document.layers){
    with (document){
        document.write('<table style="display:block" border="0" cellspacing="0" cellpadding="0"><td>')
        document.write('</td></table>')
    }
 }

通过使用 CSS class。像 :

.myClass {
   display:block;
}
// width > 768px
@media screen and (max-width: 768px){ 
  .myClass{
    display:none;
  }
}

// width < 768px
@media screen and (min-width: 768px){ 
  .myClass{
    display:none;
  }
}

通过使用 jQuery:

$( window ).resize(function() {
  // Adding table when window resized to below 500px
  if($(this).width() <= 500){
    $( "body" ).append( "<table id='dynamicTable'><tr><td>Table created</td></tr></table>");

  }else if($(this).width() > 500){
    // Removing table from DOM when window resized to above 500px
    $( "#dynamicTable" ).remove();
  }

});

我遇到过这个问题,花了我大约一个小时才解决。我与任何需要在屏幕调整大小时隐藏元素的人分享它,特别是当您的元素具有长 css 样式时: 你必须在屏幕调整大小时重写样式。例如当你有

.myClass {
    border-radius: 40px;
 }

对于主要样式和调整大小后 @media screen and (min-width: 768px),您只希望 2 个角具有 border-radius,您不能写:

.myClass {
    border-top-right-radius: 40px;
    border-bottom-right-radius: 40px;
 }

我以为在屏幕调整大小时完全删除主要样式并应用次要样式,这是完全错误的,完全相同的样式将被替换而其他样式不会。 在我的示例中,如果我只想让块的两个角具有 border-radius,我必须先移除所有角 border-radius,然后应用 border-top-right-radiusborder-bottom-right-radius,所以这将适用:

.myClass {
    border-radius: 0px;
    border-top-right-radius: 40px;
    border-bottom-right-radius: 40px;
 }

但前一个不会。 希望您理解并帮助您更快地解决问题。