简体   繁体   English

javascript js文件中的条件标签

[英]Conditional tags in javascript js file

Is there a way to use HTML conditional tags like <!--[if (IE 6)|(IE 7)]> inside a .js file as I need to execute certain javascript if visitor is using IE6 or IE7? 有没有一种方法可以在.js文件中使用HTML条件标记,例如<!--[if (IE 6)|(IE 7)]>因为如果访问者使用IE6或IE7,我需要执行某些javascript吗?

Thanks 谢谢

I'd do something like this with the markup... 我会用标记做这样的事情...

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class=""> <!--<![endif]-->
<head>

Then in your JS, you can check for the appropriate body styles: 然后在您的JS中,您可以检查适当的身体样式:

if (html tag has class lt-ie8) {
  // we're in ie7 and below land
}

You can use conditional comments in your markup, and use the result to create conditional variables in your js. 您可以在标记中使用条件注释,并使用结果在js中创建条件变量。 Start your doc with this: 使用以下命令启动您的文档:

<!DOCTYPE HTML>
<!--[if lte IE 7]><html lang="en" class="ieDetect ie7Detect"><![endif]-->
<!--[if IE 8]><html lang="en" class="ieDetect ie8Detect"><![endif]-->
<!--[if IE 9]><html lang="en" class="ieDetect ie9Detect"><![endif]-->
<!--[if !IE]>--><html lang="en"><!--<![endif]-->

I usually prefer to use jQuery for this and check for classes: 我通常更喜欢为此使用jQuery并检查类:

var ieDetect = $('.ieDetect').length
,   ie7Detect = $('.ie7Detect').length
,   ie8Detect = $('.ie8Detect').length
,   ie9Detect = $('.ie9Detect').length
;

if (ieDetect){
  // do stuff with IE
}

If you want to only use JS, you can either use a class fetching function and retain the markup above, or you could forgo the generic ieDetect class and just use ie7Detect (and 8,9) as IDs on the html tag. 如果只想使用JS,则可以使用类访存函数并保留上面的标记,也可以放弃通用的ieDetect类,而只将IE7Detect(和8,9)用作html标签上的ID。

var ie7Detect = document.getElementById("ie7Detect").length
,   etc...

Separate JS files are the best option. 最好的选择是单独的JS文件。

However you can use navigator.userAgent: 但是,您可以使用navigator.userAgent:

var userAgent = navigator.userAgent;

From this you can determine the browser the user is using to view your page and use the if statement built into JS. 由此,您可以确定用户正在使用的浏览器来查看页面,并使用JS内置的if语句。

User navigator.userAgent to check the browser the user has. 用户navigator.userAgent来检查用户拥有的浏览器。

Recommended reading: http://api.jquery.com/jQuery.support/ 推荐阅读: http : //api.jquery.com/jQuery.support/

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

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