首页 > 解决方案 > JavaScript:在移动设备上隐藏 div

问题描述

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

<div id = "NameXYZ"> 
    <script src = "// 123.com"> </ script> 
    <script src = "// 1234.com"> </ script> 
</div>

标签: javascript

解决方案


[编辑,正如 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>

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

希望你觉得这很有用。


推荐阅读