JavaScript 和 HTML
本文介紹 JavaScript 和 HTML。
YouTube Video
javascript-html-dom.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 2em;
14 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
15 background-color: #f7f9fc;
16 color: #333;
17 line-height: 1.6;
18 }
19
20 .container {
21 max-width: 800px;
22 margin: 0 auto;
23 padding: 1em;
24 background-color: #ffffff;
25 border: 1px solid #ccc;
26 border-radius: 10px;
27 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
28 }
29
30 h1, h2 {
31 font-size: 1.5rem;
32 color: #007bff;
33 margin-top: 0.5em;
34 margin-bottom: 0.5em;
35 border-left: 5px solid #007bff;
36 padding-left: 0.6em;
37 background-color: #e9f2ff;
38 }
39
40 button {
41 display: block;
42 margin: 1em auto;
43 padding: 0.75em 1.5em;
44 font-size: 1rem;
45 background-color: #007bff;
46 color: white;
47 border: none;
48 border-radius: 6px;
49 cursor: pointer;
50 transition: background-color 0.3s ease;
51 }
52
53 button:hover {
54 background-color: #0056b3;
55 }
56
57 #output {
58 margin-top: 1em;
59 background-color: #1e1e1e;
60 color: #0f0;
61 padding: 1em;
62 border-radius: 8px;
63 min-height: 200px;
64 font-family: Consolas, monospace;
65 font-size: 0.95rem;
66 overflow-y: auto;
67 white-space: pre-wrap;
68 }
69
70 .highlight {
71 outline: 3px solid #ffc107; /* yellow border */
72 background-color: #fff8e1; /* soft yellow background */
73 transition: background-color 0.3s ease, outline 0.3s ease;
74 }
75
76 .active {
77 background-color: #28a745; /* green background */
78 color: #fff;
79 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
80 transition: background-color 0.3s ease, box-shadow 0.3s ease;
81 }
82 </style>
83</head>
84<body>
85 <div class="container">
86 <h1>JavaScript Console</h1>
87 <button id="executeBtn">Execute</button>
88 <div id="output"></div>
89 </div>
90
91 <div class="container">
92 <h2>HTML Sample</h2>
93 <div id="content">Hello, World!</div>
94 <button id="changeText">Change Text</button>
95 </div>
96
97 <script>
98 // Override console.log to display messages in the #output element
99 (function () {
100 const originalLog = console.log;
101 console.log = function (...args) {
102 originalLog.apply(console, args);
103 const output = document.getElementById('output');
104 output.textContent += args.map(String).join(' ') + '\n';
105 };
106 })();
107
108 document.getElementById('executeBtn').addEventListener('click', () => {
109 // Prevent multiple loads
110 if (document.getElementById('externalScript')) return;
111
112 const script = document.createElement('script');
113 script.src = 'javascript-html-dom.js';
114 script.id = 'externalScript';
115 //script.onload = () => console.log('javascript-html-dom.js loaded and executed.');
116 //script.onerror = () => console.log('Failed to load javascript-html-dom.js.');
117 document.body.appendChild(script);
118 });
119 </script>
120</body>
121</html>JavaScript 中的 window 物件
window 物件是 JavaScript 中瀏覽器環境下的全域物件,提供與網頁及瀏覽器視窗相關的功能和資訊。由於 window 是瀏覽器的全域範疇,在瀏覽器中執行的所有 JavaScript 程式碼都成為 window 物件的一部分。window 物件在瀏覽器環境中執行 JavaScript 時扮演重要角色,提供眾多 API 和屬性。
window 物件的主要功能
屬性
1// Get and display the document's title
2console.log(`Title: ${window.document.title}`);
3
4// Get and display the current URL
5console.log(`URL: ${window.location.href}`);
6
7// Go back to the previous page
8// Note: this will navigate back in history, so be careful when running it
9console.log("Navigating back to the previous page...");
10window.history.back();
11
12// Display the browser's user agent
13console.log(`User Agent: ${window.navigator.userAgent}`);
14
15// Display the width and height of the viewport
16console.log(`Viewport Width: ${window.innerWidth}`);
17console.log(`Viewport Height: ${window.innerHeight}`);window.document:訪問當前的 HTML 文件。window.location:管理當前的 URL 和瀏覽器導航。window.history:訪問瀏覽器的歷史資訊,並允許進行前進或後退導航。window.navigator:提供有關瀏覽器和設備的資訊。window.innerWidth/window.innerHeight:獲取視窗的寬度和高度。
方法
1// Show an alert
2window.alert('Hello, this is an alert!');
3
4// Show a confirmation dialog
5if (window.confirm('Are you sure you want to proceed?')) {
6 console.log('User clicked OK');
7} else {
8 console.log('User clicked Cancel');
9}
10
11// Show a prompt dialog
12const userInput = window.prompt('Please enter your name:');
13console.log(`Hello, ${userInput}!`);
14
15// Open a new tab
16window.open('https://www.example.com', '_blank');
17
18// Display a message after 3 seconds
19window.setTimeout(() => {
20 console.log('This message appears after 3 seconds!');
21}, 3000);
22
23// Display a message every second
24const intervalId = window.setInterval(() => {
25 console.log('This message appears every second!');
26}, 1000);
27
28// Clear the interval after 5 seconds
29setTimeout(() => {
30 clearInterval(intervalId);
31 console.log('Interval cleared.');
32}, 5000);window.alert():顯示一個警示對話框。window.confirm():顯示一個確認對話框,並返回確定或取消的結果。window.prompt():顯示一個提示用戶輸入的對話框,並獲取輸入的值。window.open():打開一個新的窗口或標籤頁。window.setTimeout()/window.setInterval():設置計時器,在特定時間後或以固定間隔執行函數。
事件處理
1// Display a message when the page is fully loaded
2window.onload = () => {
3 console.log('Page is fully loaded!');
4};
5
6// Display a message when the window is resized
7window.onresize = () => {
8 console.log('Window resized! New size:', window.innerWidth, 'x', window.innerHeight);
9};
10
11// Display a message when the page is being scrolled
12window.onscroll = () => {
13 console.log('Page is being scrolled!');
14};window.onload:當網頁完全載入時會觸發此事件。window.onresize:當視窗尺寸改變時會觸發此事件。window.onscroll:當使用者捲動頁面時會觸發此事件。
作為全域變數的角色
1var myVar = 10;
2console.log(window.myVar); // 10
window物件保存了全域變數和函數。換句話說,宣告的變數和函數會自動成為window的屬性。
JavaScript中的DOM操作
JavaScript 的 DOM(文件物件模型)操作用於動態與網頁上的元素交互。DOM 將 HTML 文件的結構表示為樹狀結構,並可通過 JavaScript 改變這個結構以修改頁面佈局和控制顯示。
DOM 的基礎知識
DOM 將網頁的 HTML 視為物件,允許訪問和修改元素及屬性。使用 document 物件訪問 HTML 文件。
獲取 DOM 元素
JavaScript 有多種方法可以訪問 DOM 中的元素。
document.getElementById():根據id屬性取得元素。document.getElementsByClassName():根據類別名稱取得元素。回傳一個HTMLCollection。HTMLCollection是一個即時動態的集合,能即時反映 DOM 的變化。document.getElementsByTagName():根據標籤名稱取得元素。回傳一個HTMLCollection。document.querySelector():使用 CSS 選擇器取得第一個符合條件的元素。document.querySelectorAll():使用 CSS 選擇器取得所有符合條件的元素。回傳一個NodeList。NodeList是一個靜態集合,僅保存取得當下的狀態,不會反映後續對 DOM 的變更。
範例:getElementById 和 querySelector
1<div id="content">Hello, World!</div>
2<button id="changeText">Change Text</button>1const content = document.getElementById('content');
2console.log(content.textContent); // "Hello, World!"
3
4const button = document.querySelector('#changeText');DOM 操作
可以對獲取的元素執行各種操作。
更改文字
若要更改元素的文字,可以使用 textContent 或 innerHTML。
textContent:獲取或更改元素的文本內容。HTML 標籤不會被解析。innerHTML:獲取或更改元素的 HTML 內容。包含 HTML 標籤的字串也會被處理。
1content.textContent = 'Hello, world!'; // Change the text
2button.innerHTML = '<strong>Click to change</strong>'; // Change including HTML
更改屬性
使用 setAttribute() 和 getAttribute() 來更改元素屬性。
1button.setAttribute('disabled', 'true'); // Disable the button
2const id = content.getAttribute('id'); // Get the "content"
3console.log(id);更改CSS樣式
使用 style 屬性來更改CSS樣式。
1content.style.color = 'red'; // Change the text color to red
2content.style.fontSize = '20px'; // Change the font size
操作類名
使用 classList 向元素添加或移除類名。
add():新增 class。remove():移除 class。toggle():根據是否存在來新增或移除 class。contains():判斷是否有指定的 class。
1content.classList.add('highlight'); // Add a class
2button.classList.toggle('active'); // Toggle a class
創建和刪除DOM元素
創建新元素
使用 document.createElement() 創建新元素並將其添加到DOM中。
1const newDiv = document.createElement('div'); // Create a new div element
2newDiv.textContent = 'This is a new element';
3document.body.appendChild(newDiv); // Append to the body element
刪除元素
使用 remove() 方法刪除元素。
1newDiv.remove(); // Remove the created element
添加事件
作為DOM操作的一部分,您可以添加響應用戶互動的事件處理程式。使用 addEventListener() 來處理如點擊和鍵盤互動等事件。
1button.addEventListener('click', () => {
2 content.textContent = 'The text has been changed';
3});在此示例中,單擊按鈕會更改 #content 元素的文本。
導航DOM樹
您可以導航DOM來訪問父元素和同級元素。
parentNode:存取父節點。childNodes:存取子節點。你可以存取所有類型的節點,不僅僅是像 HTML 標籤這樣的元素節點,還有文字節點和註解節點。firstChild/lastChild:存取第一個及最後一個子元素。nextSibling/previousSibling:存取下一個及上一個兄弟元素。
1const parent = content.parentNode; // Get the parent element
2const firstChild = parent.firstChild; // Get the first child element
3console.log(firstChild);示例:向列表中添加新項目
這是一個向列表中新增項目的示例。
1// Get the container element where the HTML will be inserted
2const content = document.getElementById('content');
3
4// Create the <ul> element with id="list"
5const list = document.createElement('ul');
6list.id = 'list';
7
8// Add initial list items
9const item1 = document.createElement('li');
10item1.textContent = 'Item 1';
11list.appendChild(item1);
12
13const item2 = document.createElement('li');
14item2.textContent = 'Item 2';
15list.appendChild(item2);
16
17// Create the <button> element with id="addItem"
18const addItemButton = document.createElement('button');
19addItemButton.id = 'addItem';
20addItemButton.textContent = 'Add Item';
21
22// Append the list and button to the content container
23content.appendChild(list);
24content.appendChild(addItemButton);
25
26// Add event listener to the button
27addItemButton.addEventListener('click', () => {
28 const newItem = document.createElement('li');
29 newItem.textContent = 'New Item';
30 list.appendChild(newItem);
31});在這段程式碼中,點擊「新增項目」按鈕會向列表中新增一個新的 <li> 元素。
總結
- JavaScript 的 DOM 操作允許您在 HTML 文件中獲取、修改、建立和刪除元素。
- 您可以使用
getElementById()和querySelector()等方法來獲取元素。 - 使用
textContent或innerHTML更改文字和 HTML,並使用setAttribute()修改屬性。 - 使用
createElement()建立新元素,並使用remove()刪除元素。 - 透過事件處理,您可以建立對使用者操作做出回應的互動式網頁。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。