一. BOM
在 JavaScript 中,BOM(Browser Object Model)是一个与浏览器交互的对象模型,它提供了一些对象和方法,使 JavaScript 有能力与浏览器窗口和浏览器窗口中的元素进行交互。BOM 主要包括以下几个部分:
- Window 对象:Window 对象表示浏览器窗口,是 JavaScript 中的全局对象。所有的全局变量、函数和对象都是Window对象的成员。例如,
alert()、confirm()、prompt()、setTimeout()、clearTimeout()、setInterval()、clearInterval()
等方法都是 Window 对象的方法。 - Location 对象:Location 对象表示当前窗口的 URL,它提供了一些属性和方法,使 JavaScript有能力改变当前文档的 URL。例如,
location.href、location.reload()
等。 - Navigator 对象:Navigator对象表示浏览器的信息,包括浏览器的名称、版本、平台等。例如,
navigator.userAgent、navigator.platform
等。 - Screen 对象:Screen对象表示用户的屏幕信息,包括屏幕的宽度、高度、可用宽度、可用高度等。例如,
screen.width、screen.height
等。 - History 对象:History对象表示浏览器的历史记录,可以用来控制浏览器的前进、后退等操作。例如,
history.back()、history.forward()、history.go()
等。
需要注意的是,BOM 是浏览器环境中的特性,只有在浏览器环境中才能使用。如果在 Node.js 等非浏览器环境中使用 BOM,将会出现错误。
1.1 查看时间
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../assets/js/date.js"></script>
</head>
<body>
<script>
let now=new Date();
console.log(formatDate(now));
const df=new Date();
console.log(df);
//比正常时间少10秒
let nowTime = df.getTime();
nowTime -=1000 * 10;
console.log (formatDate(new Date(nowTime)));
console.log("9".padStart(2,"0"));//09
console.log("9".padEnd(3,"2"));//922
</script>
</body>
</html>
// 获取当前时间
const now = new Date();
// 显示当前时间
console.log(now);
// 显示小时、分钟和秒
console.log(`当前时间:${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`);
// 显示日期和时间(完整格式)
console.log(now.toLocaleString());
1.2 制作按钮定时遮罩
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BOM</title>
<script src="../assets/date.js"></script>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
* {
box-sizing: border-box;
}
#overlay {
z-index: 999;
position: absolute;
background-color: rgba(0, 0, 0, 0.241);
left: 0;
right: 0;
top: 0;
bottom: 0;
display: none;
}
@keyframes spinner-animation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(359deg);
}
}
#overlay_content {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#overlay_content>img {
height: 5rem;
width: 5rem;
animation: spinner-animation linear 2s infinite;
/* linear是一个常见的缓动函数,又叫三次贝塞尔曲线 ( cubic-bezier),缓动函数:定义属性值怎么变化。 */
}
</style>
</head>
<body>
<button id="btn">我的世界</button>
<div id="overlay">
<div id="overlay_content">
<img id="spin" src="../assets/wdsj.jpg" alt="" style="border-radius: 50%;">
</div>
</div>
<script>
let timer = null;
spin.onclick = function () {
console.log("spin click");
if (timer != null) {
clearTimeout(timer);
timer = null;
console.log("spin cleatTimeout");
}
if (intervaler != null) {
clearInterval(intervaler);
intervaler = null;
}
}
document.getElementById("btn").onclick = function () {
console.log(this);
this.disabled = true;
console.log(overlay);
overlay.style.display = "block";
timer = setTimeout(() => {
overlay.style.display = "none";
this.disabled = false;
}, 2000); //2s后结束,只进行一次
}
let intervaler = setInterval(() => {
console.log("intervaler......");
}, 1000) //每隔1s重复一次,无限循环
</script>
</body>
</html>
1.3 alert
alert()
函数用于在浏览器窗口中显示一个警告对话框,该对话框会阻塞用户与页面的交互,直到用户点击“确定”按钮。
alert()
函数的语法如下:
window.alert(message);
其中,message
是要在警告对话框中显示的文本。如果省略 window
,则默认为 window.alert()
。
alert()
函数的示例代码如下:
alert("你好,小黑子!");
当运行上述代码时,浏览器会弹出一个包含 “Hello, World!” 文本的警告对话框。用户必须点击“确定”按钮才能关闭对话框并继续与页面进行交互。
需要注意的是,alert()
函数会阻塞用户与页面的交互,因此在实际开发中应谨慎使用。在某些情况下,可以使用更加友好的方式,如模态对话框(modal dialog)等,来替代 alert()
函数。
confirm
confirm()
函数用于在浏览器窗口中显示一个带有确认和取消按钮的对话框,该对话框会阻塞用户与页面的交互,直到用户点击“确定”或“取消”按钮。
confirm()
函数的语法如下:
window.confirm(message);
其中,message
是要在对话框中显示的文本。如果省略 window
,则默认为 window.confirm()
。
confirm()
函数的示例代码如下:
const result = confirm("您确定要删除这个项目吗?");
if (result) {
console.log("用户点击了确定按钮。");
} else {
console.log("用户点击了取消按钮。");
}
当运行上述代码时,浏览器会弹出一个包含 “您确定要删除这个项目吗?” 文本的带有确认和取消按钮的对话框。用户可以选择点击“确定”或“取消”按钮。如果用户点击“确定”按钮,则 confirm()
函数返回 true
;如果用户点击“取消”按钮,则 confirm()
函数返回 false
。
需要注意的是,confirm()
函数会阻塞用户与页面的交互,因此在实际开发中应谨慎使用。在某些情况下,可以使用更加友好的方式,如模态对话框(modal dialog)等,来替代 confirm()
函数。
1.4 prompt
prompt()
函数用于在浏览器窗口中显示一个带有输入框和确认/取消按钮的对话框,该对话框会阻塞用户与页面的交互,直到用户输入文本并点击“确定”或“取消”按钮。
prompt()
函数的语法如下:
window.prompt(message, defaultValue);
其中,message
是要在对话框中显示的文本,defaultValue
是输入框的默认值(可选)。如果省略 window
,则默认为 window.prompt()
。
prompt()
函数的示例代码如下:
const result = prompt("请输入您的名字:", "默认名字");
if (result !== null) {
console.log("用户输入的名字是:" + result);
} else {
console.log("用户点击了取消按钮。");
}
当运行上述代码时,浏览器会弹出一个包含 “请输入您的名字:” 文本的带有输入框和确认/取消按钮的对话框。用户可以在输入框中输入文本,然后点击“确定”或“取消”按钮。如果用户点击“确定”按钮,则 prompt()
函数返回用户输入的文本;如果用户点击“取消”按钮,则 prompt()
函数返回 null
。
需要注意的是,prompt()
函数会阻塞用户与页面的交互,因此在实际开发中应谨慎使用。在某些情况下,可以使用更加友好的方式,如模态对话框(modal dialog)等,来替代 prompt()
函数。
1.5 setTimeout / clearTimeout
setTimeout()
函数用于在指定的时间间隔后执行一次指定的函数或代码。
setTimeout()
函数的语法如下:
window.setTimeout(function, delay, arg1, arg2, ...);
其中,function
是要执行的函数或代码,delay
是要等待的时间(以毫秒为单位),arg1, arg2, ...
是传递给 function
的参数(可选)。如果省略 window
,则默认为 window.setTimeout()
。
setTimeout()
函数的示例代码如下:
function sayHello() {
console.log("你好,小黑子!");
}
// 设置定时器
const timeoutId = setTimeout(sayHello, 3000);
// 取消定时器
clearTimeout(timeoutId);
当运行上述代码时,sayHello()
函数将在 3 秒后执行。setTimeout()
函数返回一个 timeoutId
,它是一个整数,表示定时器的唯一标识符。您可以使用 clearTimeout()
函数取消定时器。
需要注意的是,setTimeout()
函数只会执行一次指定的函数或代码。如果您需要在指定的时间间隔内重复执行指定的函数或代码,可以使用 setInterval()
函数。
1.6 setInterval / clearInterval
setInterval()
函数用于在指定的时间间隔内重复执行指定的函数或代码。
setInterval()
函数的语法如下:
window.setInterval(function, interval, arg1, arg2, ...);
其中,function
是要执行的函数或代码,interval
是要等待的时间(以毫秒为单位),arg1, arg2, ...
是传递给 function
的参数(可选)。如果省略 window
,则默认为 window.setInterval()
。
setInterval()
函数的示例代码如下:
function sayHello() {
console.log("你好,小黑子!");
}
const intervalId = setInterval(sayHello, 3000);
// 取消定时器
clearInterval(intervalId);
当运行上述代码时,sayHello()
函数将每隔 3 秒执行一次。setInterval()
函数返回一个 intervalId
,它是一个整数,表示定时器的唯一标识符。您可以使用 clearInterval()
函数取消定时器。
需要注意的是,setInterval()
函数会在指定的时间间隔内重复执行指定的函数或代码,直到您使用 clearInterval()
函数取消定时器。如果您需要在指定的时间间隔后执行一次指定的函数或代码,可以使用 setTimeout()
函数。
1.6 location.href
location.href
属性用于获取或设置当前文档的 URL。
location.href
属性的语法如下:
window.location.href;
如果省略 window
,则默认为 window.location.href
。
location.href
属性的示例代码如下:
// 获取当前文档的 URL
const currentUrl = location.href;
console.log(currentUrl);
// 设置当前文档的 URL
location.href = "https://www.baidu.com";
当运行上述代码时,currentUrl
变量将存储当前文档的 URL,然后使用 console.log()
函数将其输出到控制台。接下来,我们将当前文档的 URL 设置为 “https://www.baidu.com”,浏览器将导航到该 URL。
需要注意的是,location.href
属性可以用于获取或设置当前文档的 URL,但不能用于获取或设置当前文档的哈希值(即 URL 中的 “#” 后面的部分)。如果您需要获取或设置当前文档的哈希值,可以使用 location.hash
属性。
1.7 location.hash
location.hash
属性用于获取或设置当前文档的哈希值(即 URL 中的 “#” 后面的部分)。
location.hash
属性的语法如下:
window.location.hash;
如果省略 window
,则默认为 window.location.hash
。
location.hash
属性的示例代码如下:
// 获取当前文档的哈希值
const currentHash = location.hash;
console.log(currentHash);
// 设置当前文档的哈希值
location.hash = "#section2";
当运行上述代码时,currentHash
变量将存储当前文档的哈希值,然后使用 console.log()
函数将其输出到控制台。接下来,我们将当前文档的哈希值设置为 “#section2”,浏览器将滚动到具有该哈希值的元素(锚定位)。
需要注意的是,location.hash
属性可以用于获取或设置当前文档的哈希值,但不能用于获取或设置当前文档的 URL。如果您需要获取或设置当前文档的 URL,可以使用 location.href
属性。
二. DOM介绍
- DOM (Document Object Model):文档对象模型。
- 将 HTML 文档的各个组成部分,封装为对象。借助这些对象,可以对 HTML 文档进行增删改查的动态操作。
2.1 Element 元素的获取操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素的获取</title>
</head>
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div class="cls">div3</div>
<div class="cls">div4</div>
<input type="text" name="username"/>
</body>
<script>
// 1. getElementById() 根据id属性值获取元素对象
let div1 = document.getElementById("div1");
alert(div1);
// 2. getElementsByTagName() 根据元素名称获取元素对象们,返回数组
let divs = document.getElementsByTagName("div");
alert(divs.length);
// 3. getElementsByClassName() 根据class属性值获取元素对象们,返回数组
let cls = document.getElementsByClassName("cls");
alert(cls.length);
// 4. getElementsByName() 根据name属性值获取元素对象们,返回数组
let username = document.getElementsByName("username");
alert(username.length);
// 5. 子元素对象.parentElement属性 获取当前元素的父元素
let body = div1.parentElement;
alert(body);
</script>
</html>
2.2 Element 元素的增删改操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素的增删改</title>
</head>
<body>
<select id="s">
<option>---请选择---</option>
<option>北</option>
<option>南</option>
<option>西</option>
</select>
</body>
<script>
//1. createElement() 创建新的元素
let option = document.createElement("option");
//为option添加文本内容
option.innerText = "东";
//2. appendChild() 将子元素添加到父元素中
let select = document.getElementById("s");
select.appendChild(option);
//3. removeChild() 通过父元素删除子元素
//select.removeChild(option);
//4. replaceChild() 用新元素替换老元素
let option2 = document.createElement("option");
option2.innerText = "东";
select.replaceChild(option2, option);
</script>
</html>
2.3 Attribute 属性的操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>属性的操作</title>
<style>
.aColor{
color: blue;
}
</style>
</head>
<body>
<a>点我呀</a>
</body>
<script>
// 1. setAttribute() 添加属性
let a = document.getElementsByTagName("a")[0];
a.setAttribute("href","https://www.baidu.com");
// 2. getAttribute() 获取属性
let value = a.getAttribute("href");
//alert(value);
// 3. removeAttribute() 删除属性
//a.removeAttribute("href");
// 4. style属性 添加样式
//a.style.color = "red";
// 5. className属性 添加指定样式
a.className = "aColor";
</script>
</html>
点击跳转
2.4 Text 文本的操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本的操作</title>
</head>
<body>
<div id="小黑子"></div>
</body>
<script>
//1. innerText 添加文本内容,不解析标签
let div = document.getElementById("小黑子");
div.innerText = "我是小黑子";
//div.innerText = "<b>我是div</b>";
//2. innerHTML 添加文本内容,解析标签
div.innerHTML = "<b>我是小黑子</b>";
</script>
</html>
DOM 小结
DOM(Document Object Model):文档对象模型
Document:文档对象
Element:元素对象
Attribute:属性对象
Text:文本对象
- 元素的操作
getElementById()
getElementsByTagName()
getElementsByName()
getElementsByClassName()
子元素对象.parentElement属性
createElement()
appendChild()
removeChild()
replaceChild()
- 属性的操作
setAtrribute()
getAtrribute()
removeAtrribute()
style属性
- 文本的操作
innerText
innerHTML