笔记-手写实现简易jq

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;
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值