blog icon indicating copy to clipboard operation
blog copied to clipboard

解决IE9下报错:无法获取未定义或 null 引用的属性“remove”

Open xianzou opened this issue 5 years ago • 1 comments

解决IE9下报错:无法获取未定义或 null 引用的属性“remove”

描述

报错:Unhandled promise rejection TypeError: 无法获取未定义或 null 引用的属性“remove”

运行环境

IE9

代码

document.getElementById('bodyId').classList.remove('general-bg');

运行结果

Unhandled promise rejection TypeError: 无法获取未定义或 null 引用的属性“remove”

问题分析

classList是广泛使用的CSS类处理利器,classList的返回值显示,其本质上是DOMTokenList – DOM标记列表;

DOMTokenList这种类型表示一组空间分隔的标记。通常由HTMLElement.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList或HTMLAreaElement.relList返回。从0开始的类JavaScript数组索引。DOMTokenList始终是区分大小写的。

使用如下:

// 示例dom元素:<div id="div" class="foo bar"> </div>
var div = document.getElementById('bodyId');

div.classList.remove("foo"); //移除该div的foo 类
div.classList.add("anotherclass"); //给该div添加一个
 
// if visible is set remove it, otherwise add it
div.classList.toggle("visible"); //如果该div包含visible类则移除它,否则给它添加
 
alert(div.classList.contains("foo")); //检查当前div是否包含foo类
 
div.classList.add("foo","bar"); //添加多个CSS 类

IE9和IE9以前的版本不支持该属性(不兼容Android2.3和iOS4.2的):

image

解决方案

加入垫片

if (!("classList" in document.documentElement)) {
        Object.defineProperty(HTMLElement.prototype, 'classList', {
            get: function() {
                var self = this;
                function update(fn) {
                    return function(value) {
                        var classes = self.className.split(/\s+/g),
                            index = classes.indexOf(value);
                        
                        fn(classes, index, value);
                        self.className = classes.join(" ");
                    }
                }
                
                return {                    
                    add: update(function(classes, index, value) {
                        if (!~index) classes.push(value);
                    }),
                    
                    remove: update(function(classes, index) {
                        if (~index) classes.splice(index, 1);
                    }),
                    
                    toggle: update(function(classes, index, value) {
                        if (~index)
                            classes.splice(index, 1);
                        else
                            classes.push(value);
                    }),
                    
                    contains: function(value) {
                        return !!~self.className.split(/\s+/g).indexOf(value);
                    },
                    
                    item: function(i) {
                        return self.className.split(/\s+/g)[i] || null;
                    }
                };
            }
        });
    }

xianzou avatar Aug 01 '19 08:08 xianzou

牛皮牛皮,亲测好用! 以及这种博客写法还是第一次遇见啊,哈哈哈

SilentFlute avatar May 07 '20 10:05 SilentFlute