第十七章 DOM (simple)
事件模型
js的事件模型哪几个阶段都了解吗?那是先捕获阶段还是先冒泡阶段?
阶段:
捕获
冒泡
经过浏览器处理,都会变成规范的代码
三种等待渲染后加载的方式
window.onload = ()=>{} settimeout(()=>{}) <script> </script defer>
防抖与节流
核心是限制请求频率
防抖(debounce)--一段时间内只执行一次
机制:定时器-辞旧迎新
jsfunction debounce(delay){ let timer; return function(){ clearTimeout(timer) timer = setTimeout(()=>{ // ajax request }, delay) } } const run = debounce(1000) const btn = document.getElementById("btn") btn.onclick = run
节流(throttle)-固定间隔时间执行
- 机制:定时器-通过类似于锁的机制来保证——固定的时间间隔内至少执行一次事件处理函数
js
function throttle(delay){
// 通过一个锁来实现节流机制
let isOver = true;
let timer;
return function (){
if (isOver){
isOver = !isOver
clearTimeout(timer)
setTimeout(()=>{
// code
isOver = !isOver
}, delay)
}
}
}
const run = throttle(1000)
const btn = document.getElementById("btn")
btn.onclick = run
节点
- 文本节点 值为3 注释节点 值为8
- 标签节点 值为1 常用 文档节点 值为9
- 属性节点 值为2
- 语法
- .childNodes 获取该节点下所有子节点
- .nodetype 判断节点类型
节点对象的原型继承
js
function proto(el) {
const prototypes = [];
prototypes.push(el.__proto__);
prototypes.push(...(el.__proto__ ? proto(el.__proto__) : []));
return prototypes;
}
Objcet.assign 进行节点批量设置样式
js
HTMLElement.prototype = Object.assign(HTMLElement.prototype, {
color(color) {
this.style.color = color;
},
hide() {
this.style.display = 'none';
}
})
//原理:原型+assign进行复用,批量设置
//像普通对象一样的属性和方法都可以在节点中使用
常用DOM节点元素
document.nodeType
document.title
document.URL
document.domain
document.referrer'
document.documentElment
document.body
document.head
attributes输出标签属性的map映射
parentElement父节点
获取所有能用tagName的节点,html可见节点,不包括textNode等