简体   繁体   English

检测IE7或更低的条件评论和javascript无法正常工作

[英]Detecting if IE7 or lower with conditional comments and javascript not working

I'm trying to check if a person is using anything IE with version less than 8 or anything else. 我正在尝试检查一个人是否正在使用版本低于8或其他任何东西的IE。

I use conditional comments to declare boolean.. 我使用条件注释来声明布尔值..

<!--[if lt IE 8]>
<script type="text/javascript">var badIE = true;</script>
<![endif]-->

And now I check in my js file the boolean like this: 现在我在我的js文件中检查布尔值,如下所示:

if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}

If I use IE7 or IE6, it alerts that "You have bad IE!". 如果我使用IE7或IE6,它会警告“你的IE浏览器坏了!”。 If I use anything else, it should alert "Bueno!", but it does not. 如果我使用其他任何东西,它应该警告“Bueno!”,但事实并非如此。 What is the problem? 问题是什么?

You need to declare the badIE variable as false first in order for it to work, or else the code outside of the conditional knows nothing about badIE 您需要声明badIE变量为假第一顺序为它工作,否则该代码的条件之外一无所知 badIE

Try this: 尝试这个:

<script>
    var badIE = false;
</script>

<!--[if lt IE 8]>
<script type="text/javascript">badIE = true;</script>
<![endif]-->

<script>
if (badIE == true){
    alert('You have bad IE!');
} else {
    alert('Bueno!');
}
</script>

Not a direct answer (Neal has you covered), but you may also be interested in: http://code.google.com/p/ie7-js/ 不是直接的答案(Neal让你了解),但您可能也有兴趣: http//code.google.com/p/ie7-js/

From the page: 从页面:

IE7.js is a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. IE7.js是一个JavaScript库,使Microsoft Internet Explorer的行为类似于符合标准的浏览器。 It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6. 它解决了许多HTML和CSS问题,并使透明PNG在IE5和IE6下正常工作。

Though if you're using jQuery, keep in mind that it does many of the same things as this library. 虽然如果你使用的是jQuery,请记住它与这个库有很多相同的功能

Your conditional statement <!--[if lt IE 8]> ... <![endif]--> means that the code between those will not be executed if the web browser is not an IE version less than 8, which means var badIE will never be declared for all other browsers (ie, FireFox, IE8, IE9, Safari, etc.) 您的条件语句<!--[if lt IE 8]> ... <![endif]-->表示如果Web浏览器不是小于8的IE版本,则不会执行这些代码之间的代码,这意味着所有其他浏览器(即FireFox,IE8,IE9,Safari等)都不会声明var badIE

Because it is never declared, you are getting a silent scripting error in the background when the browser tries to execute if (badIE == true){ , which means the browser immediately stops reading the script and does not try to execute the alert('Bueno!'); 因为它永远不会被声明,所以当浏览器尝试执行if (badIE == true){ ,后台会在后台收到静默脚本错误,这意味着浏览器会立即停止读取脚本并且不会尝试执行alert('Bueno!'); statement. 声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM