2011-10-12 42 views
3

我是JS新手,每当有人通过Interent Explorer浏览器进入我的网站时,我需要检测它。所以,我做了下面的代码,我创建的div正在其他Web浏览器上编写脚本,我认为问题出在.getElementById之类。 所以说话后,下面的代码:JS中非常基本的东西

<html> 
<head> 
<script type="text/javascript"> 
var browserName=navigator.appName; 
if (browserName=="Microsoft Internet Explorer") 
{ 
document.getElementById("example"); 
} 
</script> 

</head> 
<body> 
<div id ="example">You're Using Interent Explorer. </div> 
</body> 
</html> 

非常感谢的助手。

+0

你没有对你正在寻找的元素做任何事......这个函数的意图是什么?更重要的是,你为什么要检测IE?这可以用HTML注释,即'' – Fosco

回答

6

这些HTML注释只能由Internet Explorer

<body> 
<!--[if IE]> 
    <div id ="example">You're Using Interent Explorer. </div> 
<![endif]--> 
</body> 

大部分是对CSS的时候呈现,因为你可以针对IE 6,7,8等或者比IE 7更大:

<!--[if IE 7]> 
     <link rel="stylesheet" type="text/css" href="all-ie-only.css" /> 
<![endif]--> 

Example

+0

+1这比使用jQuery更好。 – Fosco

+0

@Fosco:事实上在这里没有人使用jQuery :) – pimvdb

+0

偷走了我的想法哈哈,伟大的思想家都认为。 –

4

1首先,您应该隐藏div(display:none)。

2您需要在脚本中使用div实际执行某些操作(fiddle)。

<html> 
<head> 
<script type="text/javascript"> 
    window.onload = function(){ 
     if (navigator.appName === "Microsoft Internet Explorer") 
     { 
      document.getElementById("example").style.display = "block"; 
     } 
    } 
</script> 

</head> 
<body> 
<div id ="example" style="display:none;">You're Using Interent Explorer. </div> 
</body> 
</html> 

否则,你只需要添加的格上下文(fiddle

window.onload = function(){ 
    if (navigator.appName === "Microsoft Internet Explorer") 
    { 
     document.body.appendChild(
      document.createElement("div") 
     ).appendChild(
      document.createTextNode("You're Using Interent Explorer")); 
    } 
} 
+0

你还需要对文件运行准备或脚本将在div之前运行是 – scrappedcola

+1

的页面上完成或者你可能在你的条件标签在IE特定的CSS加载显示/隐藏该div。 –

+0

@antisainty非常感谢,我想我理解了这个问题,但它仍然无法正常工作,请解释一下scrappedcola说了些什么? –

0

首先,JavaScript不应该用来检测浏览器。就像Chrome一样,它给出了结果“Netscape”。不管怎么说回答你的问题,怎么样一种替代方案:

<html> 
<head> 
<script type="text/javascript"> 
var browserName=navigator.appName; 
if (browserName=="Microsoft Internet Explorer") 
{ 
document.getElementById("example").innerHTML="You're using Internet Explorer!"; 
} 
</script> 

</head> 
<body> 
<div id ="example"></div> 
</body> 
</html> 

它所做的是它会在特定的div元素没有内容,就是例子。只有在JavaScript检测到使用Internet Explorer时,才会在div元素中写入“您正在使用IE”。例如,您可以使用Internet Explorer检出http://www.ducksearch.in/。它显示一个警告框,如果您使用IE,某些功能可能会丢失。非常基本的JavaScript,的确如此:)

祝你好运,未来的道路上,以及所有最好的JavaScript编码。