向js中传参来动态改变div的样式

内容描述:通过三个按钮来改变一个div的样式,用js来实现,对于要修改不同的样式,需要两个参数,一个是样式名称,一个是样式值,但是在修改时只能用

v1.style[name] = value;
不能使用
v1.style.name = value;

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            border: 1px solid gray;

        }
    </style>
    <script>
        function f(name, value) {
            var v1 = document.getElementById("div1");
            v1.style[name] = value;
        }
    </script>
</head>
<body>
<input type="button" onclick="f('width','400px')" value="变宽">
<input type="button" onclick="f('backgroundColor','red')" value="变红">
<input type="button" onclick="f('display','none')" value="隐藏">
<div id="div1"></div>
</body>
</html>

效果图:

初始图:

变宽:

 

变红:

 

隐藏:

 

猜你喜欢

转载自blog.csdn.net/psjasf1314/article/details/124105842