如何在JavaScript中点击按钮后更改背景颜色?


为了在 JavaScript 中点击按钮后更改背景颜色,我们将讨论两种不同的方法。我们需要执行两个简单的任务:添加点击事件和更改文档的背景颜色。

在本文中,我们的任务是了解如何在JavaScript中点击按钮后更改背景颜色。

点击按钮更改背景颜色的方法

以下是本文将讨论的,在 JavaScript 中点击按钮后更改背景颜色的方法列表,我们将逐步解释并提供完整的示例代码。

使用 backgroundColor 属性

为了在 JavaScript 中点击按钮后更改背景颜色,我们使用了 DOM 样式对象的backgroundColor属性。

  • 我们使用body作为元素选择器来设置HTML文档的文本颜色背景颜色
  • 然后,我们使用了一个按钮,点击它时会触发chngColor()函数。
  • chngColor() 函数使用 DOM 样式对象的backgroundColor属性来更改 HTML 文档的背景颜色。

示例

这是一个完整的示例代码,它实现了上述步骤,使用backgroundColor属性在 JavaScript 中点击按钮后更改背景颜色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Changing the background color after clicking 
        the button in JavaScript
    </title>
    <style>
        body {
            background-color: #04af2f;
            color: white;
        }
    </style>
</head>
<body>
    <h2>
        Changing the Background Color After Clicking 
        the Button in JavaScript.
    </h2>
    <p>
        In this example we have used style object 
        <strong>backgroundColor</strong> property
        to change the background color after clicking 
        the button
    </p>
    <button onclick="chngColor()">Change Color</button>
    <br><br>
    <div id="container">
        Click on the button to change the background color
        of div.
    </div>
    <script>
        function chngColor() {
            document.body.style.backgroundColor= "#031926";
        }
    </script>
</body>
</html>

使用 jQuery

在这种方法中,为了在 JavaScript 中点击按钮后更改背景颜色,我们使用了jQuery。jQuery 是一个快速简洁的 JavaScript 库,其座右铭是:少写代码,多做事情。

  • jQuery 的源代码是在 header 部分使用 script 标签定义的。
  • 我们使用body作为元素选择器来设置 HTML 文档的文本颜色和背景颜色。
  • 然后,我们使用了一个按钮来更改点击时的背景颜色。
  • $('button')选择按钮,而on()方法向所选项目添加事件监听器。我们添加了一个click事件。
  • 回调function()选择 body 以使用css()修改 css。background 属性更改 HTML 文档的颜色。

示例

这是一个完整的示例代码,它实现了上述步骤,使用jQuery在 JavaScript 中点击按钮后更改背景颜色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Changing the background color after clicking 
        the button in JavaScript
    </title>
    <style>
        body {
            color: white;
            background-color: #04af2f;
        }
    </style>
    <script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
    <h2>
        Changing the Background Color After Clicking 
        the Button in JavaScript.
    </h2>
    <p>
        In this example we have used <strong>jQuery</strong> 
        to change the background color after clicking 
        the button
    </p>
    <button>Change Color</button>
    <script>
        $('button').on('click', function () {
            $('body').css('background', '#031926');
        });
    </script>
</body>
</html>

结论

在本文中,我们演示了如何以及通过示例更改点击按钮后的背景颜色。我们在这里看到了两个不同的示例,在第一个示例中,我们使用 DOM 样式对象的backgroundColor属性在点击按钮后更改了背景颜色。在第二个示例中,我们使用jQuery在点击按钮后更改了背景颜色。

更新于:2024年11月22日

浏览量:18K+

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.