JavaScript 如何点击按钮后更改背景颜色
给定一个HTML文档,任务是使用JavaScript和jQuery更改文档的背景颜色。
方法1
此方法使用JavaScript在点击按钮后更改背景颜色。使用HTML DOM Style backgroundColor属性在点击按钮后更改背景颜色。此属性用于设置元素的background-color。
示例: 此示例通过JavaScript的帮助更改背景颜色。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to change the background color
after clicking the button ?
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on button to change the
background color
</h3>
<button onclick="myFunc()">
Click here
</button>
<h2 id="GFG" style="color:green;"></h2>
<script>
let result = document.getElementById("GFG");
function changeColor(color) {
document.body.style.background = color;
}
function myFunc() {
changeColor('yellow');
result.innerHTML = "Background Color changed";
}
</script>
</body>
</html>
输出:
方法2
单击按钮后,此方法使用jQuery更改背景颜色。
- 使用text()方法将文本内容设置为所选元素。
- 使用on()方法作为所选元素和子元素的事件处理程序。
- 使用css()方法更改/设置元素的背景颜色。
示例: 这个示例通过 JQuery 来改变背景颜色。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to change the background color
after click on button in jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
Click on button to change
the background color
</h3>
<button>
Click here
</button>
<h2 id="GFG" style="color:green;"></h2>
<script>
('button').on('click', function () {
('body').css('background', '#ccc');
$('#GFG').text("Background Color Changed!");
});
</script>
</body>
</html>
输出: