<div id="demo" onclick="applycss(250,500,"red")"></div>
<script>
function applycss(){
var box = document.getElementById("this.id").style;
box.height = fisrt parameter;
box.width = second parameter;
box.backgroundColor = third parameter;
}
</script>
怎么做?我想在点击时将值250, 500, red
应用于div,以便我可以将此函数用于任何元素而无需长编码。
答案 0 :(得分:2)
试试这个
<script>
function applycss(fisrt,second,third){
var box = document.getElementById("demo").style;
box.height=fisrt;
box.width= second;
box.backgroundColor= third;
}
</script>
答案 1 :(得分:1)
您有一些语法错误,请参阅更新的代码。对于多个CSS属性,您需要创建参数值的css-string并将其设置如下:
<强> HTML:强>
<div id="demo" onclick="applycss(this, '250', '500', 'red');">Div to apply CSS</div>
<强> JS:强>
function applycss(obj, height, width, bgColor){
var cssStyle = "height: " + height + "px; ";
cssStyle += "width: " + width + "px; ";
cssStyle += "background-color: " + bgColor + ";";
if(typeof(obj.style.cssText) != 'undefined')
obj.style.cssText = cssStyle;
else
obj.setAttribute('style', cssStyle);
}