使用classList的代码在IE中不起作用?

Wes*_*ley 78 javascript internet-explorer

我正在使用以下代码,但在IE中失败了.消息是:

无法获取属性'add'的值:object为null或undefined"

我认为这只是一个IE支持问题.你如何使以下代码在IE中工作?

有任何想法吗?

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);
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 88

classListIE9及更低版本不支持该属性.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);
Run Code Online (Sandbox Code Playgroud)

  • IE11仍然在classList上出错,它不支持SVG元素上的classList. (36认同)
  • @MikeChristensen`className`属性始终存在.它以空字符串初始化.为了便于代码维护,建议使用`+ =`来添加类名. (3认同)
  • 可能没有理由做`+ =`,因为你刚刚在上面创建了3行元素. (2认同)
  • 在严格模式下,这会生成错误,因为className是只读的. (2认同)

tag*_*awa 26

正如othes提到的那样,classListIE9和更老版本都不支持.除了亚历克斯上面的替代品之外,还有一些polyfill旨在成为替代品,即只需将这些包含在您的页面中,IE就可以正常工作(着名的最后一句话!).

https://github.com/eligrey/classList.js/blob/master/classList.js

https://gist.github.com/devongovett/1381839

  • 我使用IE 11和classList似乎没有工作(在chrome中工作) (9认同)
  • @johnktejik如果你一次添加或删除多个类,它将无法在IE11,Firefox 24-和Chrome 24-中使用.那是你在做什么的? (3认同)
  • SVG元素仍然不支持classList,这些polyfill可以解决问题 (2认同)

Kev*_*ost 11

在 IE 10 和 11 中,classList 属性定义在 HTMLElement.prototype 上。

为了让它在 SVG 元素上工作,应该在 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'));
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 我们需要复制描述符,因为Element.prototype.classList = HTMLElement.prototype.classList会抛出Invalid calling object
  • 第一项检查可防止在本机支持的浏览器上覆盖该属性。
  • 第二个检查是防止在 9 之前的 IE 版本上出现错误,其中尚未实现 HTMLElement,以及在未实现 classList 的 IE9 上。

对于 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;
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 9

    /**
 * 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, ' '));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1,但是:在某些情况下,我让 `ele.getAttribute('class')` 返回 null(也许还没有设置 class 属性?) - 一个简单的 if 语句解决了它。 (2认同)

asd*_*dru 8

看一下这个

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
})
Run Code Online (Sandbox Code Playgroud)

和classList将工作!

document.getElementsByTagName("div")[0].classList
["aclass"]

document.getElementsByTagName("div")[0].classList.add("myclass")

document.getElementsByTagName("div")[0].className
"aclass myclass"
Run Code Online (Sandbox Code Playgroud)

就这样!


Alo*_*nad 5

在 Explorer 11 中 classList.add 仅适用于单个值。

Element.classList.add("classOne", "classTwo");
Run Code Online (Sandbox Code Playgroud)

在这种情况下,资源管理器仅添加第一类而忽略第二类。所以需要做:

Element.classList.add("classOne");
Element.classList.add("classTwo");
Run Code Online (Sandbox Code Playgroud)