【问题标题】:Javascript: detect if browser is IE, then hide HTMLJavascript:检测浏览器是否为 IE,然后隐藏 HTML
【发布时间】:2018-10-10 09:53:22
【问题描述】:

如果访问者使用的是 IE 浏览器,我想创建一个 JavaScript 函数来隐藏 html。我对 Stackoverflow 做了一些研究,下面是我想出的。它不起作用。谁能告诉我我做错了什么?谢谢!

HTML:

<div id="content">
  Hello
</div>

JS:

var isIE = /*@cc_on!@*/false || !!document.documentMode;


if (isIE === 'true') {
  function display() {
    document.getElementById('content').style.display="none";
  }
}

【问题讨论】:

  • P.S. display() 永远不会被调用。顺便说一句here
  • 检测您正在使用的浏览器从来都不是一个好主意,如果您检测到您需要的功能,它会更灵活,并且更具前瞻性。
  • 你还在寻找答案吗,user1726263?你没有回应 Jeroen Smink 的回答? @Keith——这并不总是可能的,至少不是用很少的代码。例如,如何特征检测浏览器是否支持 CSS 连字符('auto' 值)?
  • @FrankConijn CSS.supports("hyphens", "auto");
  • @Keith -- 在 IE 中引发错误:“'CSS' 未定义。”

标签: javascript html if-statement browser browser-detection


【解决方案1】:

你可以试试这个:

 <!DOCTYPE html>
    <html>
    <body>
    <p>What is the name(s) of your browser?</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    <script>

    function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        alert('Safari');
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
         alert('Firefox');
    }
    else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
    {
      alert('IE'); 
    }  
    else 
    {
       alert('unknown');
    }
    }
    </script>

    </body>
    </html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多