JavaScript:函数中传入css属性和值的办法

传入css属性时,按照正常的参数传递,只不过在代码中,不能使用“.”索引,必须使用[ ]索引

比如function change(addr,value),使用时:

x.style.addr = value x

x.style[addr] = value 

实例:

<!DOCTYPE html>
<html>
<head>
	<title>example</title>
</head>
<style>
	#div1{
		width: 100px;
		height: 100px;
		background-color: gray;
	}
</style>
<script>
	function toWider(attr,value){
		var x = document.getElementById('div1');
		x.style[attr] = value;
	}
	function toNarrow(attr,value){
		var x = document.getElementById('div1');
		x.style[attr] = value;
	}
</script>
<body>
	<input type="button" value="变宽" οnclick="toWider('width','200px')">
	<input type="button" value="变窄" οnclick="toNarrow('width','100px')">
	<div id="div1" ></div>
</body>
</html>

 

posted @ 2020-02-05 19:00  昨夜昙花  阅读(30)  评论(0)    收藏  举报