繁体   English   中英

如何从JavaScript函数获取参数作为文本

[英]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>

这个怎么做? 我想将值250, 500, red到div上的div上,这样我就可以对任何元素使用此函数而无需进行长时间编码。

尝试这个

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

您有一些语法错误,请参阅更新的代码。 对于多个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);
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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