Javascript 如何操作Node.prototype,使Node.style.styleProperty变为Node.styleProperty
我要做的是做出以下声明:Javascript 如何操作Node.prototype,使Node.style.styleProperty变为Node.styleProperty,javascript,Javascript,我要做的是做出以下声明: Element.style.display = "none" Element.display = "none" 与本声明相同: Element.style.display = "none" Element.display = "none" 我还想说: Element.style.background = "#fff" 执行与此相同的操作: Element.bg
Element.style.display = "none"
Element.display = "none"
与本声明相同:
Element.style.display = "none"
Element.display = "none"
我还想说:
Element.style.background = "#fff"
执行与此相同的操作:
Element.bg = "#fff"
我该怎么做
一个想法是循环使用
元素.style
的所有键,并使用javascriptgetter
和setter
提供此行为。在本例中,元素是元素的实例。下面是一个示例代码:
Object.keys(element.style).forEach(key => {
Object.defineProperty(element, key, {
get: function() {
return element.style[key];
},
set: function(newValue) {
element.style[key] = newValue;
}
});
})
使用
getter
我们访问元素.style[key]
例如元素.style.bg
,使用setter
我们可以将新值应用于元素.style[key]
例如toelement.style.bg
请提供一些关于您正在使用的语言或您试图做的事情的信息,例如废弃或尝试为一些html元素设置样式等…不,您几乎可以肯定。您熟悉吗?我只是提供一个如何实现它的概要,在该代码工作之前,它需要元素的实例@BergiWell这就是我理解这个问题的方式:D我认为OP有某种document.getElementById之类的东西,并且是通过使用元素来概括的。@Bergi更新。谢谢你的反馈我是@ssBarBee