使用 类 扩展 HTMLElement 接口

Extending HTMLElement interface with classes

我想在自定义 属性 上使用自定义对象扩展 HTMLElement 接口。这可能吗?

这是我得到的:

if (typeof HTMLElement.prototype.classList === "undefined") {
    HTMLElement.prototype.classList = function ClassList() { return this.className.split(' '); };
    HTMLElement.classList.prototype.add = function(name) {
        if (classList.indexOf(name) !== -1) {
            return;
        }
        classList[classList.length] = name;
        this.className = classList.join(' ');
    };
    HTMLElement.classList.prototype.remove = function(name) {
        var index = classList.indexOf(name);
        if (index !== -1) {
            this.className = classList.splice(index + 1, 1).join(' ');
        }
    }
}

这应该可以让您了解我需要什么。

我想为 IE9 实现我自己的 classList 功能。 在 IE 中,这将导致未定义并引发错误。

element.classList.add('fadeIn');

有没有简单的方法来实现这个?

编辑

我已经研究了一段时间,但我的知识还不够好,无法准确理解发生了什么。我仍然必须调用 document.getElementById('whatever').classList() 以避免得到 "undefined"。我希望能够在没有大括号的情况下调用 classList(当然,如果浏览器不支持 classList)

我认为您设置的原型有误。

您应该将 classList 分配给 HTMLElement.prototype,而不是直接分配给 HTMLElement 本身。

要像在本机工作一样访问它,您可以像这样设置它...

HTMLElement.prototype.classList = function()
  // ...
};

HTMLElement.prototype.classList.add = function()
  // ...
};

HTMLElement.prototype.classList.remove = function()
  // ...
};

要定义 getter(可以不带括号调用的函数),请使用 Object.defineProperty。适用于 IE9。

function getClassList()
{
    var element = this;
    var classList = this.className.split(' ');
    classList.add = function(name) {
        if (classList.indexOf(name) !== -1) {
            return;
        }
        classList.push(name);
        element.className = classList.join(' ');
    };
    classList.remove = function(name) {
        var index = classList.indexOf(name);
        if (index !== -1) {
            classList.splice(index, 1);
            element.className = classList.join(' ');
        }
    };
    return classList;
}

Object.defineProperty(HTMLElement.prototype, 'classList', { get: getClassList });