程序员scholar 程序员scholar
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
npm

(进入注册为作者充电)

  • HTML

  • CSS

  • JavaScript

    • 简介和用法
    • 变量和数据类型
    • 运算符
    • 数据类型转换
    • 选择结构
    • 循环结构
    • 数组
    • 数组遍历
    • 函数
    • Debug调试
    • DOM
    • 事件处理
    • BOM(浏览器对象模型)
      • 1. BOM简介
      • 2. window对象
        • 2.1 常用属性
        • 历史记录(history)
        • 位置(location)
        • 文档(document)
        • 导航器(navigator)
        • 屏幕(screen)
        • 内部高度(innerHeight)
        • 内部宽度(innerWidth)
        • 2.2 常用方法
        • 弹出警告框(alert)
        • 显示输入框(prompt)
        • 显示确认框(confirm)
        • 打开新窗口(open)
        • 一次性计时器(setTimeout)
        • 周期性计时器(setInterval)
        • 清除一次性计时器(clearTimeout)
        • 清除周期性计时器(clearInterval)
        • 滚动到指定位置(scrollTo)
        • 滚动指定距离(scrollBy)
        • 打印页面(print)
        • 获取焦点(focus)
        • 失去焦点(blur)
        • 关闭窗口(close)
        • 2.3 常用事件
        • 鼠标单击事件(onclick)
        • 页面加载完成事件(onload)
        • 滚动条滑动事件(onscroll)
        • 窗口大小调整事件(onresize)
        • 获得焦点事件(onfocus)
        • 失去焦点事件(onblur)
        • 页面刷新前事件(onbeforeunload)
        • 错误事件(onerror)
      • 3. location对象
        • 常用属性
        • 常用方法
      • 4. history对象
        • 常用方法
        • 示例代码
      • 5.轮播图案例
        • HTML 部分
        • CSS 部分(styles.css)
        • JavaScript 部分(carousel.js)
        • 在线效果演示
    • 自定义对象
    • 原型 (Prototype)
    • 内置对象
    • 客户端存储
    • 模块加载方案
  • 前端三剑客
  • JavaScript
scholar
2024-07-19
目录

BOM(浏览器对象模型)

# BOM

# 1. BOM简介

BOM(Browser Object Model):浏览器对象模型,用来操作浏览器窗口和框架。JavaScript由三部分组成:

  • ECMAScript:核心语法。
  • DOM(Document Object Model):文档对象模型,核心对象是document,用来操作页面文档。
  • BOM(Browser Object Model):浏览器对象模型,核心对象是window,用来操作浏览器。

BOM

# 2. window对象

window 对象是所有浏览器实现的一个对象,表示浏览器的窗口。它是 BOM 的核心对象,所有的全局 JavaScript 对象、函数和变量自动成为 window 对象的成员。

提示

注:由于 window 对象是 BOM 结构的顶层对象,所以在调用 window 的属性和方法时可以省略 window.

# 2.1 常用属性

window 对象的常用属性本质上是指向其他对象或值的引用。这些对象或值包含了关于浏览器窗口及其内容的各种信息和功能。

# 历史记录(history)

history 属性提供了浏览器会话历史的访问权限。

// 获取浏览器会话的历史条目数
console.log(window.history.length); // 输出历史记录长度
1
2

# 位置(location)

location 属性提供了当前文档的 URL 信息。

// 强制重新加载页面
 window.location.reload(true);

// 获取当前页面的 URL
console.log(window.location.href); // 输出当前页面的 URL

// 重定向到另一个 URL
window.location.href = "https://www.example.com";
1
2
3
4
5
6
7
8

# 文档(document)

document 属性表示浏览器窗口中的 HTML 文档。

// 获取当前文档的标题
console.log(window.document.title); // 输出当前文档的标题
1
2

# 导航器(navigator)

navigator 属性提供了关于浏览器的信息。

// 获取浏览器的用户代理字符串
console.log(window.navigator.userAgent); // 输出用户代理字符串
1
2

# 屏幕(screen)

screen 属性提供了关于用户屏幕的信息。

// 获取屏幕的宽度
console.log(window.screen.width); // 输出屏幕宽度
1
2

# 内部高度(innerHeight)

innerHeight 属性返回窗口的内部高度(包括滚动条)。

// 获取窗口的内部高度
console.log(window.innerHeight); // 输出窗口的内部高度
1
2

# 内部宽度(innerWidth)

innerWidth 属性返回窗口的内部宽度(包括滚动条)。

// 获取窗口的内部宽度
console.log(window.innerWidth); // 输出窗口的内部宽度
1
2

# 2.2 常用方法

# 弹出警告框(alert)

alert() 方法显示一个带有提示信息和确定按钮的警告框。

// 显示一个警告框
window.alert("这是一个警告框!");
1
2

# 显示输入框(prompt)

prompt() 方法显示一个带有提示信息、文本输入框、确定和取消按钮的输入框,返回值为输入的数据。

// 显示一个输入框,提示用户输入名字
var name = window.prompt("请输入你的名字:", "");
if (name != null && name != "") {
    console.log("你好, " + name);
}
1
2
3
4
5

# 显示确认框(confirm)

confirm() 方法显示一个带有提示信息、确定和取消按钮的确认框,确定返回 true,取消返回 false。

// 显示一个确认框,提示用户确认操作
var result = window.confirm("你确定要执行这个操作吗?");
if (result) {
    console.log("操作已确认");
} else {
    console.log("操作已取消");
}
1
2
3
4
5
6
7

# 打开新窗口(open)

open() 方法打开具有指定名称的新窗口,并加载给定 URL 所指定的文档。

// 打开一个新的窗口,加载指定的 URL
window.open("https://www.example.com", "newwindow", "width=400,height=300");
1
2
  • URL:第一个参数 "https://www.example.com" 表示要加载的页面的 URL。
  • 窗口名称:第二个参数 "newwindow" 是新窗口的名称,用于标识窗口。如果已有同名窗口,则新内容将在同一个窗口中加载。
  • 参数字符串:第三个参数 "width=400,height=300" 是一个逗号分隔的设置字符串,用于指定新窗口的各种属性,如宽度、高度、是否显示工具栏等。

# 一次性计时器(setTimeout)

setTimeout() 方法设置一次性定时器,在指定毫秒值后执行某个函数。

// 设置一个2秒后执行的定时器
window.setTimeout(function() {
    console.log("定时器到时了");
}, 2000); // 2秒后执行
1
2
3
4

# 周期性计时器(setInterval)

setInterval() 方法设置周期性定时器,周期性循环执行某个函数。

// 设置一个每2秒执行一次的定时器
var intervalId = window.setInterval(function() {
    console.log("每2秒执行一次");
}, 2000); // 每2秒执行一次
1
2
3
4

# 清除一次性计时器(clearTimeout)

clearTimeout() 方法清除一次性定时器。

// 设置一个定时器
var timeoutId = window.setTimeout(function() {
    console.log("定时器到时了");
}, 2000);

// 清除定时器,取消其执行
window.clearTimeout(timeoutId); // 清除定时器
1
2
3
4
5
6
7

# 清除周期性计时器(clearInterval)

clearInterval() 方法清除周期性定时器。

// 设置一个周期性定时器
var intervalId = window.setInterval(function() {
    console.log("每2秒执行一次");
}, 2000);

// 清除定时器,停止周期性执行
window.clearInterval(intervalId); // 清除定时器
1
2
3
4
5
6
7

# 滚动到指定位置(scrollTo)

scrollTo() 方法把内容滚动到指定的坐标,即设置滚动条的 偏移位置。

// 将页面滚动到距离顶部100像素的位置
window.scrollTo(0, 100); // 滚动到距离顶部100像素的位置
1
2

# 滚动指定距离(scrollBy)

scrollBy() 方法把内容滚动指定的像素数,即设置滚动条的 偏移量。

// 将页面向下滚动100像素
window.scrollBy(0, 100); // 向下滚动100像素
1
2

# 打印页面(print)

print() 方法打开打印对话框,打印当前文档。

// 打开打印对话框,打印当前页面
window.print(); // 打开打印对话框
1
2

# 获取焦点(focus)

focus() 方法将窗口/框架设置为获得焦点。

// 设置窗口获得焦点
window.focus(); // 窗口获得焦点
1
2

# 失去焦点(blur)

blur() 方法将焦点从窗口/框架移开。

// 设置窗口失去焦点
window.blur(); // 窗口失去焦点
1
2

# 关闭窗口(close)

close() 方法关闭当前窗口。

// 关闭当前窗口
window.close(); // 关闭当前窗口
1
2

# 2.3 常用事件

# 鼠标单击事件(onclick)

onclick 事件在鼠标单击时触发。

// 绑定鼠标单击事件
window.onclick = function() {
    console.log("鼠标单击事件");
};
1
2
3
4

# 页面加载完成事件(onload)

onload 事件在页面加载完成时触发。

// 绑定页面加载完成事件
window.onload = function() {
    console.log("页面已加载");
};
1
2
3
4

# 滚动条滑动事件(onscroll)

onscroll 事件在窗口滚动条滑动时触发。

// 绑定滚动条滑动事件
window.onscroll = function() {
    console.log("窗口正在滚动");
};
1
2
3
4

# 窗口大小调整事件(onresize)

onresize 事件在窗口大小调整时触发。

// 绑定窗口大小调整事件
window.onresize = function() {
    console.log("窗口大小已调整");
};
1
2
3
4

# 获得焦点事件(onfocus)

onfocus 事件在窗口获得焦点时触发。

// 绑定窗口获得焦点事件
window.onfocus = function() {
    console.log("窗口获得焦点");
};
1
2
3
4

# 失去焦点事件(onblur)

onblur 事件在窗口失去焦点时触发。

// 绑定窗口失去焦点事件
window.onblur = function() {
    console.log("窗口失去焦点");
};
1
2
3
4

# 页面刷新前事件(onbeforeunload)

onbeforeunload 事件在页面刷新或关闭前触发,常用于提示用户保存数据。

// 绑定页面卸载前事件
window.onbeforeunload = function(event) {
    event.returnValue = "你确定要离开此页面吗?";
};
1
2
3
4

# 错误事件(onerror)

onerror 事件在发生 JavaScript 错误时触发。

// 绑定错误事件
window.onerror = function(message, source, lineno, colno, error) {
    console.log("发生错误:", message);
};
1
2
3
4

# 3. location对象

location 对象包含了当前页面的 URL 信息,通过它可以访问和修改 URL,重新加载页面等。

# 常用属性

  • href:设置或返回完整的 URL。
  • hostname:返回 web 主机的域名。
  • pathname:返回 URL 的路径部分。
  • protocol:返回所使用的 web 协议。
  • port:返回 web 服务器使用的端口号。
  • search:返回 URL 的查询部分(问号 ? 之后的部分)。

# 常用方法

  • reload(force):重新加载当前页面。force 参数是一个布尔值,指定是否强制重新加载页面,忽略缓存。
  • assign(url):加载新的文档。
  • replace(url):用新的文档替换当前文档,不保留当前页面在会话历史中的记录。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>location 对象示例</title>
    <script type="text/javascript">
        window.onload = function() {
            // 获取当前 URL
            console.log("当前 URL:", window.location.href);

            // 获取主机名
            console.log("主机名:", window.location.hostname);

            // 获取路径
            console.log("路径:", window.location.pathname);

            // 获取协议
            console.log("协议:", window.location.protocol);

            // 获取端口号
            console.log("端口号:", window.location.port);

            // 获取查询字符串
            console.log("查询字符串:", window.location.search);

            // 修改 URL
            // window.location.href = "https://www.example.com";
            // console.log("URL 已修改为 https://www.example.com");

            // 强制重新加载页面
            // window.location.reload(true);
            // console.log("页面已重新加载");

            // 加载新的文档
            // window.location.assign("https://www.example.com");
            // console.log("加载新的文档 https://www.example.com");

            // 替换当前文档
            // window.location.replace("https://www.example.com");
            // console.log("当前文档已被 https://www.example.com 替换");
        }
    </script>
</head>
<body>
    <h1>测试 location 对象</h1>
    <!-- 在控制台中查看 location 对象的属性和方法的输出结果 -->
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

# 4. history对象

history 对象包含了用户(在浏览器窗口中)访问过的 URL。通过它可以在浏览历史中前进和后退。

# 常用方法

方法名 含义
back( ) 后退,加载 History 列表中的上一个 URL
forward( ) 前进,加载 History 列表中的下一个 URL
go(number) 浏览器移动指定的页面数

# 示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>history 对象示例</title>
    <script type="text/javascript">
        window.onload = function() {
            // 后退
            document.getElementById("back").onclick = function() {
                window.history.back();
            };

            // 前进
            document.getElementById("forward").onclick = function() {
                window.history.forward();
            };

            // 跳转到指定历史记录
            document.getElementById("go").onclick = function() {
                window.history.go(-1); // 后退一页
            };
        }
    </script>
</head>
<body>
    <button id="back">后退</button>
    <button id="forward">前进</button>
    <button id="go">跳转到指定历史记录</button>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 5.轮播图案例

# HTML 部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图示例</title>
    <link rel="stylesheet" href="css/carousel.css">
</head>
<body>
    <div class="carousel">
        <!-- 轮播图图片 -->
        <img src="images/image1.jpg" alt="Image 1" class="active">
        <img src="images/image2.jpg" alt="Image 2">
        <img src="images/image3.jpg" alt="Image 3">
        <img src="images/image4.jpg" alt="Image 4">

        <!-- 轮播图指示器 -->
        <div class="carousel-indicators">
            <div class="active">1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
        </div>

        <!-- 添加左右箭头 -->
        <div class="carousel-control prev">&lt;</div>
        <div class="carousel-control next">&gt;</div>
    </div>
    <script src="js/carousel.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# CSS 部分(styles.css)

.carousel {
    width: 600px; /* 设置轮播图的宽度,可以根据需要调整 */
    height: 300px; /* 设置轮播图的高度 */
    margin: 0 auto; /* 使轮播图水平居中 */
    overflow: hidden; /* 隐藏超出轮播图容器的内容 */
    position: relative; /* 使轮播图容器内的元素可以使用绝对定位 */
}

.carousel img {
    width: 100%; /* 图片宽度设为容器宽度的100%,使图片自适应容器宽度 */
    height: 100%; /* 图片高度设为容器高度的100%,使图片自适应容器高度 */
    display: none; /* 默认隐藏图片 */
    position: absolute; /* 使图片绝对定位在容器内 */
    top: 0; /* 图片顶部对齐容器顶部 */
    left: 0; /* 图片左侧对齐容器左侧 */
}

.carousel img.active {
    display: block; /* 显示当前激活的图片 */
}

.carousel-indicators {
    position: absolute; /* 使指示器绝对定位在容器内 */
    bottom: 10px; /* 指示器距离容器底部10px */
    left: 50%; /* 指示器水平居中 */
    transform: translateX(-50%); /* 通过平移实现真正的居中效果 */
    display: flex; /* 使用flex布局,使指示器横向排列 */
}

.carousel-indicators div {
    width: 20px; /* 指示器的宽度 */
    height: 20px; /* 指示器的高度 */
    background-color: #fff; /* 指示器的背景颜色 */
    color: #000; /* 指示器的文本颜色 */
    text-align: center; /* 使文本居中 */
    line-height: 20px; /* 使文本在垂直方向上居中 */
    margin: 0 5px; /* 指示器之间的间距 */
    cursor: pointer; /* 鼠标悬停时显示为指针 */
}

.carousel-indicators .active {
    background-color: #000; /* 激活状态指示器的背景颜色 */
    color: #fff; /* 激活状态指示器的文本颜色 */
}

.carousel-indicators div:hover {
    background-color: #000; /* 鼠标悬停时指示器的背景颜色 */
    color: #fff; /* 鼠标悬停时指示器的文本颜色 */
}

/* 样式定义左右箭头 */
.carousel-control {
    position: absolute; /* 使箭头绝对定位在容器内 */
    top: 50%; /* 箭头垂直居中 */
    transform: translateY(-50%); /* 通过平移实现真正的居中效果 */
    width: 30px; /* 箭头的宽度 */
    height: 30px; /* 箭头的高度 */
    background-color: rgba(0, 0, 0, 0.5); /* 箭头的背景颜色,带有透明度 */
    color: white; /* 箭头的文本颜色 */
    text-align: center; /* 使文本居中 */
    line-height: 30px; /* 使文本在垂直方向上居中 */
    font-size: 20px; /* 箭头的字体大小 */
    cursor: pointer; /* 鼠标悬停时显示为指针 */
    user-select: none; /* 禁止用户选中文字 */
}

.carousel-control.prev {
    left: 10px; /* 左箭头距离容器左侧10px */
}

.carousel-control.next {
    right: 10px; /* 右箭头距离容器右侧10px */
}

.carousel-control:hover {
    background-color: rgba(0, 0, 0, 0.8); /* 鼠标悬停时箭头的背景颜色,带有更高的透明度 */
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

# JavaScript 部分(carousel.js)

window.onload = function () {
    let currentIndex = 0; // 当前显示的图片索引
    const images = document.querySelectorAll('.carousel img'); // 获取所有图片元素
    const indicators = document.querySelectorAll('.carousel-indicators div'); // 获取所有指示器元素
    const totalImages = images.length; // 图片总数

    // 显示指定索引的图片
    function showImage(index) {
        // 移除当前活动状态
        images[currentIndex].classList.remove('active');
        indicators[currentIndex].classList.remove('active');

        // 更新当前索引
        currentIndex = index;

        // 显示新的活动状态
        images[currentIndex].classList.add('active');
        indicators[currentIndex].classList.add('active');
    }

    // 显示下一张图片
    function showNextImage() {
        let nextIndex = (currentIndex + 1) % totalImages; // 计算下一个图片的索引
        showImage(nextIndex);
    }

    // 显示上一张图片
    function showPrevImage() {
        let prevIndex = (currentIndex - 1 + totalImages) % totalImages; // 计算上一个图片的索引
        showImage(prevIndex);
    }

    // 自动轮播
    const intervalId = setInterval(showNextImage, 3000); // 每隔3秒切换一次图片

    // 添加指示器的点击事件
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            showImage(index);
            // clearInterval(intervalId); // 清除自动轮播
        });
    });

    // 添加左右箭头的点击事件
    document.querySelector('.carousel-control.prev').addEventListener('click', () => {
        showPrevImage();
        // clearInterval(intervalId); // 清除自动轮播
    });

    document.querySelector('.carousel-control.next').addEventListener('click', () => {
        showNextImage();
        // clearInterval(intervalId); // 清除自动轮播
    });
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

# 在线效果演示

编辑此页 (opens new window)
上次更新: 2025/01/25, 22:32:05
事件处理
自定义对象

← 事件处理 自定义对象→

Theme by Vdoing | Copyright © 2019-2025 程序员scholar
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式