1.如何获取dom节点
- const div = document.getElementById('div')//元素
- const pList = document.getElementsByTagName('p')//集合
- const containerLists = document.getElementsByClassName('container')//集合
- const pList = document.querySelectorAll('p') //集合
- property 和 attribute(两者都会引起dom渲染)
property修改的是原有的一些html属性,不会体现到html结构上,如 div.style.width
attribute 通过setAttribute 设置属性,然后getAttribut获取属性,修改html属性,会改变html结构
3.优化dom性能
- 对dom查询做缓存
- 将频繁的dom操作改成一次性操作(通过创建frag)
const ul = document.getElementById("container")
const frag = document.createDocumentFragment()
for(let i=0;i<20;i++){
const li = document.createElement('li')
li.innerText+= i
frag.appendChild(li)
}
ul.appendChild(frag)
4.BOM
- navigator
const ua = navigator.userAgent
const isChrome = ua.indexOf('Chrome')
console.log(isChrome)
-
location location.search 是搜索路径的带着?以及以后的内容 location.hash是搜索路径带着#以及以后的内容
-
history
history.back()向后退history.forward()前进
-
event.stopPropagation()阻止冒泡 event.preventDefault()阻止默认事件
function bindEvent(ele,type,fn){
ele.addEventListener(type,fn)
}
--------
function bindEle(ele,type,selector,fn){
if(fn == null){
fn = selector
selector = null
}
ele.addEventListener(type,(e)=>{
const target = e.target
if(selector){
if(target.matches(selector)){
fn.call(target,e)
}
}else{
fn.call(target,e)
}
})
}
const container = document.getElementById('container')
bindEle(container,'click','a',function(e){
e.preventDefault()
console.log()
alert(this.innerHTML)
})