JavaScript动态修改Div背景色实现
作者:半夏时间:2026-10-29 12:21:37浏览:354
本文介绍如何使用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背景色的全部内容,希望读者能够喜欢。
作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
