简体   繁体   中英

How to get a parameter form a javascript function as text

<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>

How to do this? I want to apply value 250, 500, red to div on click so that I can use this function to any element without long coding.

try this

<script>
     function applycss(fisrt,second,third){
        var box = document.getElementById("demo").style;
          box.height=fisrt;
          box.width=  second;
          box.backgroundColor= third;
}
 </script>

You have some syntax error, see updated code. For multiple CSS properties, you need to create css-string of your parameter values and set it as following:

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);
}

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM