首頁 >web前端 >js教程 >如何使用 JavaScript 來變更網頁的背景顏色?

如何使用 JavaScript 來變更網頁的背景顏色?

DDD
DDD原創
2024-11-14 18:39:02694瀏覽

How can I change the background color of a webpage using JavaScript?

Altering the Background Color with JavaScript

Changing the background color of a webpage with JavaScript is a straightforward task. Here's how to do it:

Solution:

  1. Access the document body: Utilize the document.body property.
  2. Modify the background style: Set the background property of document.body.style. For instance, to set it to red, use document.body.style.background = 'red'.

Here's a sample function to achieve this:

function changeBackground(color) {
   document.body.style.background = color;
}

Toinvoke the function, add the following code to the page's onload event handler:

window.addEventListener("load",function() { changeBackground('red') });

Note:

Consider the page's structure. If the background is set to a specific DIV container, you need to modify its background color instead of the document body.

以上是如何使用 JavaScript 來變更網頁的背景顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn