方法一:
<!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>