问题描述
我有JavaScript代码可以使用 classList
对象添加和删除类。
根据预期,该代码正常工作,直到我收到投诉,因为它在Opera和IE8中无效。
我不想使用任何框架或代码库。我想减少到最大程度的代码,我必须在我的程序中更改,所以我想要自己的 classList
对象,并将其添加到节点对象。我已经有这个代码:
if(typeof(document.createElement('input')。classList)=='undefined' ){
HTMLElement.prototype.classList = new function(){
this.add = function(addClass){
this.className + = addClass;
}
}
}
显然,工作。
问题是:我无法访问这个对象的 HTMLElement.className
。我该怎么做呢?如何使这个对象的工作类似于或完全像原来的那样?
Mozilla在这里列出了一个classList shim: / p>
代码中有相当一部分,但是看起来是你以后的。
I have JavaScript code that adds and removes classes using the classList
object.The code is up and working correctly as expected until I received complaints about it because it does not work in Opera and in IE8.
I don't want to use any frameworks or code libraries. I'd like to reduce to a max the code I have to change in my program so I wanted to make my own classList
object and add it to the node object. I already have this code:
if (typeof(document.createElement('input').classList) == 'undefined') {
HTMLElement.prototype.classList = new function () {
this.add = function (addClass) {
this.className += addClass;
}
}
}
which, obviously, does not work.The problem is: I can't access the HTMLElement.className
of this object like this. How can I accomplish that? How can I make this object to work similar to or exactly like the original?
Mozilla has listed a classList shim here:
http://developer.mozilla.org/en/DOM/element.classList
There's quite a bit going on in the code, but looks to be what you are after.
这篇关于当浏览器本身不实现时,创建我自己的classList对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!