js实现点击切换背景颜色

方法一:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#col{
				width: 300px;
				height: 100px;
				background-color: #ccc;
			}
		</style>
	</head>
	<body>
		<button onclick="getCol('blue')">蓝色</button>
		<button onclick="getCol('red')">红色</button>
		<button onclick="getCol('#ff6699')">紫色</button>
		<div id="col"></div>
		
		<script>
			
			function getCol(cole) {
				document.getElementById("col").style.background = cole;
			}
			
		</script>
	</body>
</html>

方法二:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#col{
				width: 300px;
				height: 100px;
				background-color: #ccc;
			}
		</style>
	</head>
	<body>
		<button id="on1">蓝色</button>
		<button id="on2">红色</button>
		<button id="on3">紫色</button>

		<div id="col"></div>
		<script>
			//获取元素
			function getId(ids) {
				return document.getElementById(ids);
			}
			//绑定事件
			function getOn(getid,color) {
				getid.onclick = function() {
					getId("col").style.background = color;
				}	
			}
			//调用函数
			getOn(getId('on1'),"blue");
			getOn(getId('on2'), "red");
			getOn(getId('on3'), "#ff6699");

		</script>
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值