简体   繁体   English

IE9 Javascript classList属性

[英]IE9 Javascript classList Property

IE9不支持classList属性,反正这行JavaScript使其可以在IE9中工作

this.wrap.classList.add("myClass") 

There are polyfills, but if you don't want to use one: Since className is a space-separated list of the classes, you could use a regular expression: 有polyfill,但是如果您不想使用它,则:由于className是用空格分隔的类列表,因此可以使用正则表达式:

return /(?:^|\s)myClass(?:$|\s)/.test(document.body.className);

(Sadly, we can't just use \\b [word boundary] since - qualifies as a word boundary, but isn't a separator in the class list.) (遗憾的是,我们不能仅使用\\b [单词边界],因为-作为单词边界,但不是类列表中的分隔符。)

An alternative: 替代:

 const hasClass = ($element, className) => { const match = new RegExp(`(^|\\\\s)${className}(\\\\s|$)`).test($element.className); return $element.className && match; }; const $el = document.querySelector('.foo'); alert(hasClass($el, 'foo')); 
 .foo { background: tomato; } 
 <div class="foo">Foobar</div> 

Building on the previous answers, if you don't want to have to deal with the nitty gritty of regexes yourself, you could import jQuery and use jQuery's .hasClass() method instead. 在前面的答案的基础上,如果您不想自己亲自处理正则表达式,可以导入jQuery并使用jQuery的.hasClass()方法。

return $(document.body).hasClass("myClass");

jQuery handles dealing with cross-browser support. jQuery处理跨浏览器支持。

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

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