簡體   English   中英

JavaScript:在移動設備上隱藏Div

[英]JavaScript: Hide a Div on Mobile

我想為小於480像素的移動設備隱藏div。 從480分辨率開始較小,整個div應該不再出現,並且無法加載javascript。 你會怎么做?

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

[由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語句並包含腳本。

希望對您有用。

謝謝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>

暫無
暫無

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

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