Javascrpt:在移动设备上隐藏Div

时间:2019-01-27 14:41:17

标签: javascript

我想为小于480像素的手机隐藏一个div。从480分辨率开始较小,整个div应该不再出现,并且无法加载javascript。你会怎么做?

.block__element {
  font-size: 12px;
}

[lang=ar] .block__element {
  font-size: 14px;
}

.block__element--small {
  font-size: 10px;
}

// ^ Basically the same as this but more specific
[lang=ar] .block__element--small {
  font-size: 10px;
}

2 个答案:

答案 0 :(得分:1)

[由Gavin Simpson编辑认为,此解决方案存在缺陷,因为如果用户旋转设备,该解决方案将无法使用]

您可以使用JavaScript确定是否应加载脚本。

为此,您可以使用以下代码替换正在使用的代码。

 <div id = "NameXYZ"> 
  <script>
    //Determine if the device have the dissired size, information about MatchMedia here: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
    if (window.matchMedia("(min-width: 480px)").matches) {
      //if the size matches, write the scripts to the document 
      document.write('<script src = "// 123.com"> </ script> ');
      document.write('<script src = "// 1234.com"> </ script> ');
    }  
  </script>
</ div>

此代码将检查屏幕的高度是否大于480px,如果大于,则返回“ true”,因此将执行if语句并包含脚本。

希望您觉得这很有用。

答案 1 :(得分:0)

感谢ithan-它有效:

    <div id="NameXYZ"> 
  <script>
    //Determine if the device have the dissired size, information about MatchMedia here: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
    if (window.matchMedia("(min-width: 480px)").matches) {
      //if the size matches, write the scripts to the document 
      document.write('<script src="//123.com"><\/script> ');
      document.write('<script src="//1234.com"><\/ script> ');
    }  
  </script>
</div>