如何在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.com/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.