好吧,假设我们创建了一个 DOM 元素:
let element = document.createElement('div');
现在,如果我想在上面应用样式,我们可以说:
element.style = 'display: inline-block; width: 50%; height: 100px; background: #f00;';
我们也可以这样说:
elemenet.style.display = 'inline-block';
elemenet.style.width = '50%';
elemenet.style.height = '100px';
elemenet.style.background = '#f00';
这种方法重复太多,因为当您应用多种样式时,您总是会说 element.style.
。
在类似 jQuery 的语法中,我们可以在 jQuery 的 $.css()
方法中应用键值对对象,如下所示:
$(element).css({
display: 'inline-block',
width: '50px',
height: '100px',
background: '#f00'
});
话虽如此,我们可以说:
let styles = {
display: 'inline-block',
width: '50px',
height: '100px',
background: '#f00'
};
for(let property in styles) {
if(styles.hasOwnProperty(property)) {
element.style[property] = styles[property];
}
}
这将应用元素
中的所有样式。我什至可以编写一个函数,比方说 applyCSS(element, styles)
并执行与上面相同的操作。
但是,在最后一种情况下,如果我们执行以下操作:
element.style = {
display: 'inline-block',
width: '50px',
height: '100px',
background: '#f00'
};
这根本不会飞。这根本行不通,并且不会对元素应用任何样式。
我的问题是:如何在 DOM 中为 style
正确应用键值对?
最佳答案
您仍然可以乱用 CSSStyleDeclaration
原型(prototype)来添加您的函数。但如果不格外小心并添加很多我没有在这里做的验证,我不会这样做。
一个例子:
CSSStyleDeclaration.prototype.setStyles = function(styles){
for(let property in styles) {
if(styles.hasOwnProperty(property) && property in this) {
this[property] = styles[property];
}else{
console.error('no property ' + property);
}
}
};
document.body.style.setStyles({
color: 'red',
foo: 'bar',
});
<span>text</span>
编辑 将 CSS2Properties 更改为 CSSStyleDeclaration
EDIT2 添加了一些其他的可能性
您也可以扩展 HTMLElement
原型(prototype),如下所示:
HTMLElement.prototype.setStyles = function(styles){
for(let property in styles) {
if(styles.hasOwnProperty(property) && property in this.style) {
this.style[property] = styles[property];
}else{
console.error('no property ' + property);
}
}
};
document.body.setStyles({
color: 'red',
foo: 'bar',
});
<span>text</span>
但最安全的方法是使用您自己的 HTML 元素类,有点像 jQuery,并且不要弄乱重要对象的原型(prototype):
function myHTMLElement(selection){
//you can use this function as a selector like jQuery, testing the type of "selection" is a string and use querySelector
var construct = function(selection){
this._element = selection;
};
//defining it on prototype means all instances will use same function
construct.prototype.setStyles = function(styles){
if(this._element && this._element.style){
for(let property in styles) {
if(styles.hasOwnProperty(property) && property in this._element.style) {
this._element.style[property] = styles[property];
}else{
console.error('no property ' + property);
}
}
}
return this;
};
return new construct(selection);
};
myHTMLElement(document.body).setStyles({
color: 'red',
foo: 'bar',
});
<span>text</span>
关于javascript - 如何在 DOM 中的键值对中应用样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179943/