使用onchange事件,当点击不同下拉框选项时,改变div背景颜色以及文字
-
效果展示
-
代码演示
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>onchange()</title>
<style type="text/css">
#div {
width: 300px;
height: 300px;
border: 2px solid gray;
margin: 100px 0 0 200px;
}
</style>
<script type="text/javascript">
//补充代码
window.onload = function() {
var mydiv = document.getElementById('div');
var mycolor = document.getElementById('color');
var colorval = mycolor.value;
mycolor.onchange = function() {
colorval = mycolor.value;
if (colorval == 0) {
mydiv.style.backgroundColor = 'white';
mydiv.innerHTML = '我没有发生任何变化';
} else {
mydiv.style.backgroundColor = colorval;
mydiv.innerHTML = '我的背景颜色变成了' + colorval + '色';
}
}
}
</script>
</head>
<body>
<div>
<span>请选择您喜欢的颜色:</span>
<select id="color">
<option value="0">请选择</option>
<option value="yellow">黄色</option>
<option value="orange">橘色</option>
<option value="pink">粉色</option>
<option value="purple">紫色</option>
</select>
</div>
<div id="div">我是div</div>
</body>
</html>