笔记-手写实现简易jq

129 阅读1分钟
function $(...args) {
    return new Jq(...args);
}

class Jq {
    // root 在操作当前的时候,传入上一次的操作对象    
    constructor(selector, root) {
        this.pervObject = root || $(document, {})
        // selector判断传入的类型
        if (typeof selector === 'string') {
            let dom = document.querySelectorAll(selector);
            this.getDom(dom);
        } else if (typeof selector === 'object') {
            this.getDom(selector);
        } else if (typeof selector === 'function') {
            window.addEventListener("DOMContentLoaded", selector)
        }
    }

    // 向this存元素
    getDom(selector) {
        if (selector.length === undefined) {
            this[0] = selector;
            this.length = 1;
        } else {
            for (let i = 0; i < selector.length; i++) {
                this[i] = selector[i];
            }
            this.length = selector.length;
        }
    }

    eq(index) {
        return $(this[index], this);
    }

    end() {
        // end方法返回上次操作的对象  用pervObject来存上次的对象
        return this.pervObject;
    }

    click(cb) {
        for (let i = 0; i < this.length; i++) {
            this[i].addEventListener("click", cb);
        }
        return this; //链式调用
    }

    on(events, cb) {
        // 字符串传入 同时可以设置多个事件用空格隔开
        events = events.split(" ").filter(item => item);
        for (let i = 0; i < events.length; i++) {
            for (let j = 0; j < this.length; j++) {
                this[j].addEventListener(events[i], cb);
            }
        }
        return this; //链式调用
    }

    css(...args) {
        // 判断css方法入参类型 可接受两种类型
        if (typeof args[0] === 'string') {
            // 判断是参数个数 获取还是设置
            if (args[1]) {
                Jq.setStyle(this[0], args[0], args[1])
            } else {
                return Jq.getStyle(this[0], args[0])
            }
        } else if (typeof args[0] === 'object') {
            for (const key in args[0]) {
                Jq.setStyle(this[0], key, args[0][key])
            }
        }
        return this; //链式调用
    }

    /**
     * static静态方法 Jq.xx访问
     */
    // 获取元素的具体属性
    static getStyle(el, attr) {
        if ($.cssHooks && attr in $.cssHooks) {
            return $.cssHooks[attr].get(el);
        }
        return getComputedStyle(el)[attr];
    }

    // 设置元素的具体属性
    static setStyle(el, attr, val) {
        if ($.cssHooks && attr in $.cssHooks) {
            // cssHooks里有样式,将设置权返回
            $.cssHooks[attr].set(el, val);
        } else {
            el.style[attr] = val;
        }
    }
}