Javascript 带有 classList 的代码在 IE 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8098406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code with classList does not work in IE?
提问by Wesley
I'm using the following code, but having it fail in IE. The message is:
我正在使用以下代码,但在 IE 中失败。消息是:
Unable to get value of the property 'add': object is null or undefined"
无法获取属性“添加”的值:对象为空或未定义”
I assume this is just an IE support issue. How would you make the following code work in IE?
我认为这只是一个 IE 支持问题。您将如何使以下代码在 IE 中工作?
Any ideas?
有任何想法吗?
var img = new Image();
img.src = '/image/file.png';
img.title = 'this is a title';
img.classList.add("profilePic");
var div = document.createElement("div");
div.classList.add("picWindow");
div.appendChild(img);
content.appendChild(div);
回答by Rob W
The classList
property is not supported by IE9 and lower. IE10+ supports it though.
Use className += " .."
instead. Note: Do not omit the space: class names should be added in a white-space separated list.
classList
IE9 及更低版本不支持该属性。不过 IE10+ 支持它。
使用className += " .."
来代替。注意:不要省略空格:类名应添加到以空格分隔的列表中。
var img = new Image();
img.src = '/image/file.png';
img.title = 'this is a title';
img.className += " profilePic"; // Add profilePic class to the image
var div = document.createElement("div");
div.className += " picWindow"; // Add picWindow class to the div
div.appendChild(img);
content.appendChild(div);
回答by tagawa
As mentioned by othes, classList
is not supported by IE9 and older. As well as Alex's alternative above, there are a couple of polyfills which aim to be a drop-in replacement, i.e. just include these in your page and IE should just work (famous last words!).
正如其他人所提到的,classList
IE9 及更早版本不支持。除了上面 Alex 的替代方案外,还有一些 polyfills 旨在成为替代品,即只需将这些包含在您的页面中,IE 就可以正常工作(著名的遗言!)。
https://github.com/eligrey/classList.js/blob/master/classList.js
https://github.com/eligrey/classList.js/blob/master/classList.js
回答by Ritesh Kumar
/**
* Method that checks whether cls is present in element object.
* @param {Object} ele DOM element which needs to be checked
* @param {Object} cls Classname is tested
* @return {Boolean} True if cls is present, false otherwise.
*/
function hasClass(ele, cls) {
return ele.getAttribute('class').indexOf(cls) > -1;
}
/**
* Method that adds a class to given element.
* @param {Object} ele DOM element where class needs to be added
* @param {Object} cls Classname which is to be added
* @return {null} nothing is returned.
*/
function addClass(ele, cls) {
if (ele.classList) {
ele.classList.add(cls);
} else if (!hasClass(ele, cls)) {
ele.setAttribute('class', ele.getAttribute('class') + ' ' + cls);
}
}
/**
* Method that does a check to ensure that class is removed from element.
* @param {Object} ele DOM element where class needs to be removed
* @param {Object} cls Classname which is to be removed
* @return {null} Null nothing is returned.
*/
function removeClass(ele, cls) {
if (ele.classList) {
ele.classList.remove(cls);
} else if (hasClass(ele, cls)) {
ele.setAttribute('class', ele.getAttribute('class').replace(cls, ' '));
}
}
回答by asdru
check this out
看一下这个
Object.defineProperty(Element.prototype, 'classList', {
get: function() {
var self = this, bValue = self.className.split(" ")
bValue.add = function (){
var b;
for(i in arguments){
b = true;
for (var j = 0; j<bValue.length;j++)
if (bValue[j] == arguments[i]){
b = false
break
}
if(b)
self.className += (self.className?" ":"")+arguments[i]
}
}
bValue.remove = function(){
self.className = ""
for(i in arguments)
for (var j = 0; j<bValue.length;j++)
if(bValue[j] != arguments[i])
self.className += (self.className?" " :"")+bValue[j]
}
bValue.toggle = function(x){
var b;
if(x){
self.className = ""
b = false;
for (var j = 0; j<bValue.length;j++)
if(bValue[j] != x){
self.className += (self.className?" " :"")+bValue[j]
b = false
} else b = true
if(!b)
self.className += (self.className?" ":"")+x
} else throw new TypeError("Failed to execute 'toggle': 1 argument required")
return !b;
}
return bValue;
},
enumerable: false
})
and classList will work!
和 classList 将工作!
document.getElementsByTagName("div")[0].classList
["aclass"]
document.getElementsByTagName("div")[0].classList.add("myclass")
document.getElementsByTagName("div")[0].className
"aclass myclass"
that's all!
就这样!
回答by Kevin Drost
In IE 10 & 11, The classList property is defined on HTMLElement.prototype.
在 IE 10 和 11 中,classList 属性定义在 HTMLElement.prototype 上。
In order to get it to work on SVG-elements, the property should be defined on Element.prototype, like it has been on other browsers.
为了让它在 SVG 元素上工作,应该在 Element.prototype 上定义该属性,就像在其他浏览器上一样。
A very small fix would be copying the exact propertyDescriptor from HTMLElement.prototype to Element.prototype:
一个非常小的修复是将确切的 propertyDescriptor 从 HTMLElement.prototype 复制到 Element.prototype:
if (!Object.getOwnPropertyDescriptor(Element.prototype,'classList')){
if (HTMLElement&&Object.getOwnPropertyDescriptor(HTMLElement.prototype,'classList')){
Object.defineProperty(Element.prototype,'classList',Object.getOwnPropertyDescriptor(HTMLElement.prototype,'classList'));
}
}
- We need to copy the descriptor, since
Element.prototype.classList = HTMLElement.prototype.classList
will throwInvalid calling object
- The first check prevents overwriting the property on browsers which support is natively.
- The second check is prevents errors on IE versions prior to 9, where HTMLElement is not implemented yet, and on IE9 where classList is not implemented.
- 我们需要复制描述符,因为
Element.prototype.classList = HTMLElement.prototype.classList
会抛出Invalid calling object
- 第一项检查可防止在本机支持的浏览器上覆盖该属性。
- 第二个检查是防止在 9 之前的 IE 版本上出现错误,其中尚未实现 HTMLElement,以及在未实现 classList 的 IE9 上。
For IE 8 & 9, use the following code, I also included a (minified) polyfill for Array.prototype.indexOf, because IE 8 does not support it natively (polyfill source: Array.prototype.indexOf
对于 IE 8 & 9,使用以下代码,我还为 Array.prototype.indexOf 包含了一个(缩小的)polyfill,因为 IE 8 本身不支持它(polyfill 来源:Array.prototype.indexOf
//Polyfill Array.prototype.indexOf
Array.prototype.indexOf||(Array.prototype.indexOf=function (value,startIndex){'use strict';if (this==null)throw new TypeError('array.prototype.indexOf called on null or undefined');var o=Object(this),l=o.length>>>0;if(l===0)return -1;var n=startIndex|0,k=Math.max(n>=0?n:l-Math.abs(n),0)-1;function sameOrNaN(a,b){return a===b||(typeof a==='number'&&typeof b==='number'&&isNaN(a)&&isNaN(b))}while(++k<l)if(k in o&&sameOrNaN(o[k],value))return k;return -1});
// adds classList support (as Array) to Element.prototype for IE8-9
Object.defineProperty(Element.prototype,'classList',{
get:function(){
var element=this,domTokenList=(element.getAttribute('class')||'').replace(/^\s+|\s$/g,'').split(/\s+/g);
if (domTokenList[0]==='') domTokenList.splice(0,1);
function setClass(){
if (domTokenList.length > 0) element.setAttribute('class', domTokenList.join(' ');
else element.removeAttribute('class');
}
domTokenList.toggle=function(className,force){
if (force!==undefined){
if (force) domTokenList.add(className);
else domTokenList.remove(className);
}
else {
if (domTokenList.indexOf(className)!==-1) domTokenList.splice(domTokenList.indexOf(className),1);
else domTokenList.push(className);
}
setClass();
};
domTokenList.add=function(){
var args=[].slice.call(arguments)
for (var i=0,l=args.length;i<l;i++){
if (domTokenList.indexOf(args[i])===-1) domTokenList.push(args[i])
};
setClass();
};
domTokenList.remove=function(){
var args=[].slice.call(arguments)
for (var i=0,l=args.length;i<l;i++){
if (domTokenList.indexOf(args[i])!==-1) domTokenList.splice(domTokenList.indexOf(args[i]),1);
};
setClass();
};
domTokenList.item=function(i){
return domTokenList[i];
};
domTokenList.contains=function(className){
return domTokenList.indexOf(className)!==-1;
};
domTokenList.replace=function(oldClass,newClass){
if (domTokenList.indexOf(oldClass)!==-1) domTokenList.splice(domTokenList.indexOf(oldClass),1,newClass);
setClass();
};
domTokenList.value = (element.getAttribute('class')||'');
return domTokenList;
}
});
回答by Alonad
In Explorer 11 classList.add works with single values only.
在 Explorer 11 中 classList.add 仅适用于单个值。
Element.classList.add("classOne", "classTwo");
In this case Explorer adds only first class and ignores the second one. So need to do:
在这种情况下,资源管理器仅添加第一类而忽略第二类。所以需要做:
Element.classList.add("classOne");
Element.classList.add("classTwo");
回答by Juan Mendes
classList
is not supported in IE < 9. Use jQuery.addClassor a polyfill like the one at https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
classList
IE < 9 不支持。使用jQuery.addClass或类似https://developer.mozilla.org/en-US/docs/Web/API/Element/classList 中的 polyfill