[英]What is the standard solution to get body class at IE8 and other browsers with javascript
I need to get body class at internet explorer 8 and lower, i'm using the javascript classList method but it seems that it's not working on old IE browsers ( http://caniuse.com/#search=classList ), is there any standard solution for new browser and the oldest one? 我需要在Internet Explorer 8及更低版本上获取主体类,我正在使用javascript classList方法,但似乎在旧版IE浏览器上不起作用( http://caniuse.com/#search=classList ),是否有新浏览器和最旧浏览器的标准解决方案?
var b = document.body;
// check body class
if (!b.classList.contains('ie-8')) {
b.classList.add('ie-block');
// removing DOM main container
b.removeChild('mainContainer');
}
Thx for help. 谢谢。
You can use the standard .className
property , which contains a space-separated list of the classes. 您可以使用标准
.className
属性 ,该属性包含以空格分隔的类列表。
Also there's an error in your code: the line b.removeChild('mainContainer');
您的代码中也有错误:
b.removeChild('mainContainer');
is wrong: the removeChild
method takes an Element
as argument , and you are giving a string to it instead. 是错误的:
removeChild
方法将Element
作为参数 ,而您给它提供了一个字符串。 You should first get that element (which I suppose is the element with id="mainContainer"
, and then remove it properly. 您应该首先获取该元素 (我想是具有
id="mainContainer"
的元素, 然后正确删除它 。
Stated the above, you can then check if the body's className
contains the desired class and behave consequently , here's a working example: 如上所述,您可以然后检查身体的
className
包含所需的类并因此进行操作 ,这是一个工作示例:
var b = document.body;
if (~(" "+b.className+" ").indexOf(" ie-8 ")) {
b.className += " ie-block";
b.removeChild(document.getElementById("mainContainer"));
}
Additional notes: 补充笔记:
className
because classNames do not usually begin/end with a space, but they separate classes with spaces, so you'll need to check for " ie-8 "
(with leading spaces), because matching it without spaces can result in a wrong identification (eg a class like "some-ie-8-thing"
would match). className
因为className通常不以空格开头/结尾,但是它们将类与空格分开,因此您需要检查" ie-8 "
(带有前导空格),因为与之匹配没有空格会导致错误的标识(例如,将匹配"some-ie-8-thing"
类的类)。 ~(...).indexOf
because the ~
operator will return 0
(which is false
) only if the number returned by indexOf
is -1
, which means that the espression will evaluate to true only if the string contains the given substring. ~(...).indexOf
因为~
运算符仅在indexOf
返回的数字为-1
时才返回0
(这是false
),这意味着仅当字符串包含给定子字符串。 " ie-block"
because of classes being separated with spaces. " ie-block"
的开头添加了空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.