JavaScript动态修改Div背景色实现

作者:半夏

时间:2026-10-29

浏览:353

本文介绍如何使用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背景色的全部内容,希望读者能够喜欢。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章