JS-DOM与BOM
DOM
DOM(Document Object Model) 文档对象模型
是W3C组织制定并推荐的标准, 这个标准提供了一系列操作HTML的统一API(Application Programming Interface)
核心对象是document
浏览器的工作流程
- 浏览器读取HTML文件
- 在内存中生成DOM树
- 调用API渲染显示
DOM树
DOM树
是将HTML文档映射成树形结构,通过节点对象对其处理,处理的结果可以加入到当前的页面
-
文档: 一个HTML页面就是一个文档,DOM中使用document表示
-
节点: 网页中的所有内容,在DOM树中都是一个节点(标签、属性、文本、注释等)
-
- 元素节点: 网页中的所有内容, 比如
h1
,div
都是一个元素, 也就是element Node - 文本节点:
<h1>文本</h1>
里的文本就是文本节点, 也就是text Node - 属性节点:
<img src="1.jpg"></img>
里的属性就是属性节点
- 元素节点: 网页中的所有内容, 比如
获取元素
如果要操作DOM, 首先我们需要知道具体需要操作哪一个元素. 即: 获取元素
目前最常用的API
- getElementById(兼容性好)
- querySelector(H5新增, 功能强大)
- querySelectorAll(H5新增)
document.querySelector('选择器') // 元素选择器, 如: li // id选择器, 如: #nav // class选择器, 如: .box
<div id="time">2024-10-02</div> <script> var div = document.getElementById('time') console.log(div) console.dir(div) </script>
<body> <div class="box">盒子1</div> <div class="box">盒子2</div> <div id="nav"> <ul> <li>首页</li> <li>产品</li> </ul> </div> <script> // querySelector 返回指定选择器的第一个元素对象 var firstBox = document.querySelector('.box') console.log(firstBox) var nav = document.querySelector('#nav') console.log(nav) var li = document.querySelector('li') console.log(li) // querySelectorAll()返回指定选择器的所有元素对象集合 var allBox = document.querySelectorAll('.box') console.log(allBox) var lis = document.querySelectorAll('li') console.log(lis) </script> </body>
事件驱动
步骤
- 获取元素
- 注册事件(绑定事件)处理函数
- 触发事件, 执行函数
鼠标事件
事件名 | 触发条件 |
---|---|
onclick | 鼠标单点 |
onblur | 失去焦点 |
onfocus | 获得焦点 |
onmouseover | 鼠标经过 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .box { position: relative; width: 70px; height: 90px; margin: 100px auto; padding-top: 4px; border: 1px solid #ccc; font-size: 12px; text-align: center; color: #ff5000; } .box img { width: 62px; margin-top: 4px; } .box .close_btn { position: absolute; top: -1px; left: -23px; width: 20px; height: 20px; border: 1px solid #ccc; font-style: normal; color: #ccc; } </style> </head> <body> <div class="box"> 去领红包 <img src="images/tao.png" alt="" /> <i class="close_btn">x</i> </div> <script> // 需求. 仿淘宝的效果. 点击x号, 关闭广告 // 一. 获取DOM元素 var box = document.querySelector('.box') var btn = document.querySelector('.close_btn') // 二. 绑定事件, 修改属性 btn.onclick = function () { // 修改属性 box.style.display = 'none' } </script> </body> </html>
键盘事件
事件名 | 触发条件 |
---|---|
onkeyup | 按键松开时触发 |
onkeydown | 按键按下时触发 |
onkeypress | 按键按下时触发, 不能识别ctrl, shift等功能键, 区分大小写 |
事件监听
domObj.addEventListener('click', function() { // 回调函数 alert(22); })
事件对象
domObj
比较常用的属性和方法
- e.target: 触发事件的对象
<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> var ul = document.querySelector('ul') ul.addEventListener('click', function (e) { // 我们给ul 绑定了事件 那么this 就指向ul console.log(this) // 如果是li 触发了事件 会向上冒泡, e.target表示li console.log(e.target) }) </script> </body>
<body> <script> // 键盘事件对象中的keyCode属性可以得到相应键的ASCII码值 // 1. keyup 和keydown事件不区分字母大小写 a 和 A 得到的都是65 // 2. keypress 事件 区分字母大小写 a 97 和 A 得到的是65 document.addEventListener('keyup', function(e) { // console.log(e); console.log('up:' + e.keyCode); // 我们可以利用keycode返回的ASCII码值来判断用户按下了那个键 if (e.keyCode === 65) { alert('您按下的a键'); } else { alert('您没有按下a键') } }) document.addEventListener('keypress', function(e) { // console.log(e); console.log('press:' + e.keyCode); }) </script> </body>
- e.preventDafult(): 阻止默认行为
<body> <a href="http://www.baidu.com">baidu</a> <script> const a = document.querySelector('a') a.addEventListener('click', function (e) { // 阻止默认行为 e.preventDefault() }) </script> </body>
- e.stopPropagation(): 阻止冒泡
<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> const li = document.querySelector('li') const ul = document.querySelector('ul') li.addEventListener('click', function (e) { e.stopPropagation() console.log('li被点击了') }) ul.addEventListener('click', function () { console.log('ul被点击了') }) </script> </body>
示例: 实现一个留言板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <style> * { margin: 0; padding: 0; } body { padding: 100px; } textarea { width: 200px; height: 100px; border: 1px solid skyblue; outline: none; resize: none; } ul { margin-top: 50px; } li { width: 300px; margin: 15px 0; padding: 5px; background-color: blueviolet; color: #fff; } </style> </head> <body> <textarea name="" id=""></textarea> <button>发布</button> <ul></ul> <script> // 1. 获取元素 var btn = document.querySelector('button') var text = document.querySelector('textarea') var ul = document.querySelector('ul') // 2. 注册事件 btn.onclick = function () { if (text.value == '') { alert('您没有输入内容') return false } else { // (1) 创建元素 var li = document.createElement('li') // 先有li 才能赋值 li.innerHTML = text.value // (2) 添加元素 ul.insertBefore(li, ul.children[0]) text.value = '' } } </script> </body> </html>
BOM
BOM(Browser Object Model)
浏览器对象模型
它提供了独立于内容而与浏览器窗口进行交互的对象,其核心对象是 window
,
由于每个浏览器厂商实现方式不同, BOM的表现会略有差异.
BOM 由一系列相关的对象构成,并且每个对象都提供了很多方法与属性
包括:
- location: URL相关
- navigator: 浏览器相关
- screen: 窗口相关
- history: 浏览历史
定时器
- setTimeout():
当时间到了, 会执行函数. 只执行一次
setTimeout(function() { console.log('1s') }, 1000)
- setInterval():
每隔一段时间, 执行一次函数. 会执行多次
setInterval(function() { console.log('1s') }, 1000)
- clearInterval():
停止setInterval设置的定时器
var counter = 3 var id = setInterval(function () { if (counter <= 0) { clearInterval(id) console.log('时间到了') } else { console.log('还剩' + counter + '秒') counter-- } }, 1000)
对比:
<body> <button onclick="stop()">停止计时</button> <script> // 参数1: 回调函数, 当时间结束时调用的函数 // 参数2: 计时时间, 单位是ms setTimeout(() => { console.log('一次性定时器') }, 1000) console.log('先执行') const timeId = setInterval(() => { console.log('周期性定时器, 每隔1s执行一次') }, 1000) function stop() { clearInterval(timeId) } </script> </body>
示例 - 模拟发送验证码倒计时
<body> 手机号码: <input type="text" /> <button>发送</button> <script> var btn = document.querySelector('button') var timer = 3 btn.addEventListener('click', function (e) { btn.disabled = true var id = setInterval(function () { if (timer <= 0) { clearInterval(id) btn.innerHTML = '发送' btn.disabled = false timer = 3 return } btn.innerHTML = timer + '秒后重试' timer-- }, 1000) }) </script> </body>
location对象
location对象用于获取设置URL
Schema://host[:port]/path[?query-string]#anchor
-
Schema: 使用的协议类型, 如http/https/ftp等
-
host: 主机域名或IP
-
port: 端口号(可选)
-
path: 路径
-
query-string: 查询参数(可选)
-
#anchor: 锚链接
-
常用属性
属性名 | 说明 |
---|---|
location.href | 获取或者设置 URL |
location.pathname | 返回路径部分 |
location.hash | 返回#后面的锚链接 |
<body> <button>登录</button> <script> // 1. 获取dom对象 const btn = document.querySelector('button') // 2. 监听点击事件 btn.addEventListener('click', function () { let count = 3 // 启动定时器 const id = setInterval(() => { if (count <= 0) { clearInterval(id) console.log('时间到了...') // 跳转 window.location.href = './home.html' } else { console.log(`剩余${count}秒`) } count-- }, 1000) }) </script> </body>
本文作者:Khru
本文链接:https://www.cnblogs.com/khrushchefox/p/18573260
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步