我基本上尝试使用简单的函数更新元素的指定样式属性的值(不会弄乱或覆盖其他样式属性)。例如,此功能允许您输入" top"作为参数并访问/编辑element.style.top的值(或者相反,如果输入" left"则为element.style.left。)
对于某些上下文,我的特定功能将允许用户通过移动其边缘的位置来调整元素的大小(从而更改顶部,底部,左侧或右侧定位属性),以便分配的值动态响应用户&#39输入(因此不能由CSS类预先确定)。
我想到的一些可能性:
function changeStyleAttribute(el,attr) { //doesn't work (wrong syntax?)
el.style.attr = new_value
}
function changeStyleAttribute(el,attr) { //doesn't work (wrong syntax?)
el.setAttribute("style.attr",new_value)
}
function changeStyleAttribute(el,attr) { //could work but seems hack-y?
el.setAttribute(attr,new_value) //overwrites all style attributes with property of interest
el.classList.add(old_classes) //re-introduces all other default attributes of the element
}

我觉得在原生的javascript中我可能会有一种更直接,更优雅的方法,而我却错过了吗?
答案 0 :(得分:0)
如果属性的键是动态值或变量,请使用Square bracket notation
注意:您没有设置属性,而是添加/修改css规则。
function changeStyleAttribute(el, cssRule) {
el.style[cssRule] = value;
}