我正在尝试使用 javascript 设计 DIV 的样式。如果用户点击DIV,它会动态改变onclick后传递的属性的值。我想尝试这个以保存我的代码,这就是我选择 jquery css 的原因。但是,该属性不起作用。这是可能的还是有其他方法可以实现?谢谢
<script>
function changeProperty(mine , property , value){
$(mine).css({ property : value }); //if I change the property to 'background' for example, it works properly, but I want property to remain so that i will not be changing the property from time to time
}
</script>
<div onclick="changeProperty(this, 'background', 'red');">
change background
</div>
<div onclick="changeProperty(this, 'font-size', '15px');">
change font size
</div>
<div onclick="changeProperty(this, 'font', 'Arial');">
change font
</div>
最佳答案
那是因为您向 css
方法传递了一个包含 property
属性的对象。在这种情况下,最好将两个参数传递给 css
方法:
function changeProperty(mine , property , value){
$(mine).css(property, value);
}
但是,如果你想传递一个对象,你可以动态构建它:
function changeProperty(mine , property , value){
var obj = {};
obj[property] = value;
$(mine).css(obj);
}
另一个改进是在函数内部使用 this
值(在这种情况下与 mine
相同):
function changeProperty(property , value){
$(this).css(...);
}
然后在 HTML 中您将拥有 changeProperty.call(this, "font", "Arial")
。
.css( propertyName, value )
Set one or more CSS properties for the set of matched elements.
propertyName
: A CSS property name.Type:
String
value
: A value to set for the property.Type: String or Number
关于javascript - 如何使用jquery动态改变css的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501529/