在 JavaScript 中更改背景颜色
本教程将讨论如何使用 JavaScript 中的 backgroundColor
属性更改背景颜色。
使用 JavaScript 中的 backgroundColor
属性更改背景颜色
我们可以使用 JavaScript 中的 backgroundColor
属性更改背景颜色。要使用此属性,你需要获取要更改其背景颜色的元素,然后你可以使用 backgroundColor
属性来设置背景颜色。
例如,让我们使用 HTML 创建一个页面,并使用 backgroundColor
属性将正文的背景颜色更改为绿色。请参考下面的代码。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
document.body.style.backgroundColor = 'green';
</script>
</body>
</html>
你还可以使用类的 id 或名称获取元素。要使用其 id 获取元素,你可以使用 getElementById()
函数。要使用其类获取元素,你可以使用 getElementsByClassName()
函数。
例如,让我们通过 id 获取元素并使用 backgroundColor
属性更改其背景颜色。请参考下面的代码。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id='myID'>
Hello Wold
</p>
<script type="text/javascript">
document.getElementById('myID').style.backgroundColor = 'green';
</script>
</body>
</html>
上面的代码只会更改 id 为 myID
的元素的背景颜色,而不是整个 body 部分。你还可以使用不同颜色的颜色代码来更改元素的背景颜色,而不是使用颜色名称来更改它。
让我们编写一个代码来使用按钮更改文本的背景颜色。请参考下面的代码。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onClick="Mycolor()">Change Color</button>
<div id="myID">Hello World</div>
<script type='text/javascript'>
function Mycolor() {
var element = document.getElementById("myID");
element.style.backgroundColor='#900';
}
</script>
</body>
</html>
在此代码中,你将看到一个按钮和一个文本。当你按下按钮时,文本的背景颜色将根据给定的颜色发生变化。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。