本文介绍如何使用JavaScript通过DOM操作动态修改HTML元素的背景颜色。通过获取元素ID并修改style.backgroundColor属性,结合按钮点击事件,实现点击不同按钮切换Div颜色为蓝色、粉色或黑色的功能。
JavaScript动态修改Div背景色实现
使用JavaScript控制Div背景颜色
<html>
<head>
</head>
<style>
#div1{width:400px;height:400px;background-color:red;}
</style>
<script>
function blue(){
div1=document.getElementById('div1');
div1.style.backgroundColor='blue';
}
function pink(){
div1=document.getElementById('div1');
div1.style.backgroundColor='pink';
}
function black(){
div1=document.getElementById('div1');
div1.style.backgroundColor='black';
}
</script>
<body>
<button onclick='wr();'>生成文字</button>
<button onclick='blue();'>blue</button>
<button onclick='pink();'>pink</button>
<button onclick='black();'>black</button>
<div id='div1'>
</div>
以上就是本文介绍的关于通过JavaScript动态修改Div背景色的全部内容,希望读者能够喜欢。