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():添加类名。remove():移除类名。toggle():根据类名是否存在添加或移除类名。contains():检查类名是否存在。
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频道。