DOM封装

938 阅读3分钟

对象风格

window.dom 是我们提供的全局对象

以下比喻如有不当,请谅解
弟弟指位于当前节点的下一个节点
哥哥指位于当前节点的上一个节点
儿子指当前元素子节点
爸爸指当前元素父级节点

dom.create(`<div>hi</div>`)//用于创建节点
dom.after(node,node2)//用于新增弟弟
dom.befor(node,node2)//用于新增哥哥
dom.append(parent,child)//用于新增儿子
dom.wrap(`<div></div>`)//用于新增爸爸

dom.remove(node)//用于删除节点
dom.empty(parent)//用于删除后代

dom.attr(node,'title',?)//用于读属性
dom.text(node,?)//用于读写文本内容
dom.html(node,?)//用于读写HTML内容
dom.style(node,{color:'red'})//用于修改style
dom.class.add(node,'blue')//用于添加class
dom.class.remove(node,'blue')//用于删除class
dom.on(node,'click',fn)//用于添加事件
dom.off(node,'click',fn)//用于删除事件监听

find(selector,scope) //用于获得标签或者标签们
parent(node)//用于获取父元素
children(node)//用于获取子元素
siblings(node)//用于获取兄弟姐妹元素
next(node)//用于获取弟弟
previous(node)//用于获取哥哥
each(nodeList, fn)//用于遍历所有节点
index(node)//用于获取排行榜第几

HTML代码

<!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>封装DOM</title>
    <style>
        .red {
            background: red;
        }
    </style>
</head>

<body>
    <div id="test">test</div>
    <div id="empty">
        <div id="e1"></div>
        <div id="e2"></div>
        <div id="e3"></div>
    </div>
    <div id="test2">
        <p class="red">段落标签3</p>
    </div>
    <div id="siblings">
        <div id="s1"></div>
        <div id="s2"></div>
        <div id="s3"></div>
    </div>
    <div id="travel">
        <div id="t1">t1</div>
        <div id="t2">t2</div>
        <div id="t3">t3</div>
    </div>
    
    <script src="dom.js"></script>
    <script src="main.js"></script>


</body>

</html>

JS 封装代码


window.dom = {
    create(string) {
      const container = document.createElement("template");
      container.innerHTML = string.trim();
      return container.content.firstChild;
    },
    after(node,node2){
        node.parentNode.insertBefore(node2,node.nextSibling);
    },
    before(node,node2){
        node.parentNode.insertBefore(node2,node)
    },
    append(parent,node){
        parent.appendChild(node)
    },
    wrap(node,parent){
        dom.before(node,parent)
        dom.append(parent,node)
    },
    remove(node){
        node.parentNode.removeChild(node)
        return node
    },
    empty(node){
        // node.innerHTML = ''
        // const {childNodes}= node //childNodes = node.childNodes 的缩写
        const array = []
        let x = node.firstChild
        while(x){
            array.push(dom.remove(node.firstChild))
            x = node.firstChild
        }
        return array
    },
    attr(node,name,value){
        if(arguments.length === 3){//重载
            node.setAttribute(name,value)
        }else if(arguments.length === 2){
            return node.getAttribute(name)
        }
    },
    text(node,string){//适配
        if(arguments.length === 2){
            if('innerText' in node){
                node.innerText = string;
            }
            else{
                node.textContent = string;
            }
        }else if(arguments.length === 1){
            if('innerText' in node){
                return node.innerText
            }
            else{
                return node.textContent
            }
        }
        
    },
    html(node,string){
        if(arguments.length === 2){
            node.innerHTML = string
        }else{
            return node.innerHTML
        }
    },
    style(node,name,value){
        if(arguments.length === 3){
           node.style[name] = value
        }else if((arguments.length === 2 )&&(typeof name === 'string')){
            return node.style[name]
        }else if(name instanceof Object){
            for(let key in name){
                node.style[key] = name[key]
            }
        }
    },
    class:{
        add(node,className){
            node.classList.add(className)
        },
        remove(node,className){
            node.classList.remove(className)
        },
        has(node,className){
            return node.classList.contains(className)
        }
    },
    on(node,eventName,fn){
        node.addEventListener(eventName,fn)
    },
    off(node,eventName,fn){
        node.removeEventListener(eventName,fn)
    },
    find(selector,scope){
        return (scope || document).querySelectorAll(selector)
    },
    parent(node){
        return node.parentNode
    },
    children(node){
        return node.children
    },
    siblings(node){
        return Array.from(node.parentNode.children).filter(n=>n!==node)
    },
    next(node){
        let x = node.nextSibling
        while(x && x.nodeType === 3){
            x = x.nextSibling
        }
        return x
    },
    previous(node){
        let x = node.previousSibling
        while(x && x.nodeType === 3){
          x = x.previousSibling
        }
        return x
      },
      each(nodeList, fn){
        for(let i=0;i<nodeList.length;i++){
          fn.call(null, nodeList[i])
        }
      },
      index(node){
        const list = dom.children(node.parentNode)
        let i
        for(i=0;i<list.length;i++){
          if(list[i] === node){
            break
          }
        }
        return i
      }
}

JS调用代码


const div = dom.create(`<div id="div1">newDiv</div>`)
dom.after(test,div);
console.log(div)
const div3 = dom.create(`<div id="parent"></div>`)
dom.wrap(test,div3)
const nodes = dom.empty(window.empty)
console.log(nodes)
dom.attr(test,'title',`Hi, I am Frank`)
const title = dom.attr(test,'title')
console.log(`title:${title}`)
dom.text(test,`你好这是新的内容`)
dom.text(test)
dom.style(test,{border:'1px solid red',color:'blue'})
console.log(dom.style(test,'border'))
dom.style(test,'border','1px solid black')
dom.class.add(test,'red')
dom.class.remove(test,'red')
console.log(dom.class.has(test,'red'))

const fn = ()=> {console.log('点击了')}
dom.on(test,'click',fn)
dom.off(test,'click',fn)
const testDiv = dom.find('#test')[0];
console.log(testDiv)
const test2 = dom.find('#test2')[0];
console.log(dom.find('.red',test2)[0]);
console.log(dom.parent(test));

const s2 = dom.find('#s2')[0]
console.log(dom.siblings(s2))
console.log(dom.next(s2))
console.log(dom.previous(s2))

const t = dom.find('#travel')[0]
dom.each(dom.children(t), (n)=> dom.style(n, 'color', 'red'))

console.log(dom.index(s2))