如何在 JavaScript 中使用 document.body?
在本教程中,我們將學習如何在 JavaScript 中使用 document.body。
在 JavaScript 中使用 document.body 屬性獲取文件的 body 部分,即 <body> 標籤。<body> 標籤定義了文件的主體。HTML 文件的全部內容,包括所有標題、段落、影像、超連結、表格、列表和其他元素,都包含在 <body> 元素中。
在一個 HTML 文件中,只能有一個 <body> 元素。
在本教程中,我們將使用 JavaScript 中的 document.body 來完成以下操作:
- 更改 body 的背景顏色
- 在 body 的末尾新增一個新元素
使用 document.body 更改 body 的背景顏色
在 JavaScript 中,document.body 包含 body 標籤的所有屬性和方法。例如,backgroundColor 屬性指定 body 標籤的背景顏色,這意味著可以使用此屬性修改整個文件的 body 顏色。backgroundColor 屬性在 document.body 的 style 物件中可用,因此我們可以在 JavaScript 程式碼中輕鬆使用它。
語法
document.body.style.backgroundColor = color
在上面的語法中,我們使用 document.body 的 backgroundColor 屬性來更改 body 的背景顏色。'color' 是顏色名稱或顏色程式碼。
示例
在下面的示例中,我們使用 JavaScript 中的 document.body 來更改 body 的背景顏色。我們使用一個名為“更改背景顏色”的按鈕,該按鈕與一個點選事件相關聯。每當使用者點選按鈕時,都會執行一個點選處理程式函式;在本例中,它是“changeBg()”函式。此函式使用 document.body 和 backgroundColor 屬性來更改 body 的背景顏色。
<html> <body> <h2>Change the background color of the body using the <i>document.body</i> in JavaScript</h2> <button onclick = "changeBg()"> Change background-color </button> <p>Click on the above button to change the background color of the body!</p> <script> // 'Change background-color' click event handler funtion function changeBg() { // using the document.body document.body.style.backgroundColor = 'rgb(226, 255, 196)' } </script> </body> </html>
使用 document.body 在 body 的末尾新增一個新元素
在 JavaScript 中,我們必須首先使用 document.createElement() 方法建立元素,才能在 body 的末尾新增一個新元素。其次,我們需要在新的元素中新增一些內容,然後使用 document.body 的 appendChild() 方法,我們可以將這個新元素新增到 body 標籤的末尾。
語法
// creating new element const newElement = document.createElement(type) newElement.innerHTML = 'It is a new element' // adding a new element at the end of the body document.body.appendChild(newElement)
在上面的語法中,我們使用 document.createElement() 方法建立元素,'type' 是使用者想要建立的元素型別。document.body 的 appendChild() 方法用於在 body 的末尾新增一個新元素。
示例
在下面的示例中,我們使用 JavaScript 中的 document.body 在 body 的末尾新增一個新元素。一個名為“新增新元素”的按鈕與一個點選事件相關聯,該事件會在使用者點選按鈕時執行一個點選處理程式函式。此函式使用 document.body 和 document.createElement() 方法建立一個型別為“p”的新元素,並將其新增到 body 的末尾。
<html> <body> <h2>Add a new element at the end of the body using the <i>document.body</i> in JavaScript</h2> <button onclick = "addNewElement()"> Add new element</button> <p>Click on the above button to add a new element at the end of the body!</p> <script> // 'Add new element' click event handler funtion function addNewElement() { // creating new element const newElement = document.createElement('p') newElement.innerHTML = 'It is a new element' // adding a new element at the end of the body document.body.appendChild(newElement) } </script> </body> </html>
本教程教我們如何在 JavaScript 中使用 document.body。我們討論了 document.body 的兩種用途。在第一個示例中,我們使用 document.body 更改 body 的背景顏色,在第二個示例中,我們在 body 的末尾新增一個新元素。建議您通讀並練習這些示例,以更好地理解 document.body 的作用。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP