Home  >  Article  >  Web Front-end  >  How to change color using javascript

How to change color using javascript

青灯夜游
青灯夜游Original
2022-01-23 18:19:049338browse

How to use javascript to change the color: 1. Use the "element object.style.color = "color value";" statement to change the text color; 2. Use "element object.style.backgroundColor = "color value" ";" statement to change the background color.

How to change color using javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Use javascript to change the color

1. Use the color property of the Style object to change the text color

The color attribute sets the color of the text.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<div id="box">元素内容</div><br />
		<button onclick="myFunction()">改变文本颜色</button>
		<script>
			function myFunction() {
				var box = document.getElementById("box");
				box.style.color = "red";
			}
		</script>
	</body>

</html>

How to change color using javascript

2. Use the backgroundColor property of the Style object to change the background color

The backgroundColor property can set the background color of the element.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<div id="box">元素内容</div><br />
		<button onclick="myFunction()">改变背景颜色</button>
		<script>
			function myFunction() {
				var box = document.getElementById("box");
				box.style.backgroundColor = "red";
			}
		</script>
	</body>

</html>

How to change color using javascript

【Related recommendations: javascript learning tutorial

The above is the detailed content of How to change color using javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn