JS中非常基础的东西

时间:2011-10-12 20:04:05

标签: javascript

我是JS的新手,每当有人使用Interent Explorer浏览器进入我的网站时,我都需要检测。所以,我制作了以下代码,我创建的div正在其他Web浏览器上编写脚本我假设问题出在.getElementById等。 所以在谈话之后,这是代码:

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

非常感谢帮助者。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>

否则,您只需在上下文中添加div(fiddle

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

答案 2 :(得分: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中所有最好的编码。