动手实现JQuery(选择元素设置属性)

发布于 24 天前  30 次阅读


大家对于$符号很熟悉,我现在的公司对jq进行了封装,调用的方法是finedo,这次总结一下jq是如何实现$().css()的

代码贴出来了,如果看不懂,那你可能就需要去了解下prototype和proto了,

https://www.jianshu.com/p/dee9f8b14771

或者去b站看一下pink老师的视频也行

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
</head>

<body>
    <div id="main">main</div>
    <script src="./apesblog.js" type="text/javascript"></script>
    <script>
        apesblog("#main").css("color", "red");
    </script>

    <script>
        
    </script>
</body>

</html>
(function () {

    var Apesblog = function (dom) {
        return new Apesblog.prototype.init(dom);
    }

    Apesblog.prototype = {
        // constructor: Apesblog,
        init: function (dom) {
            if (dom.indexOf("#") == 0) {
                dom = dom.substr(1, dom.length);
                console.log(dom);
                this.elem = document.getElementById(dom);
            }
            // this.__proto__ = Apesblog.prototype;
           
            console.log(this);
        },

        css: function (key, value) {
            this.elem.style[key] = value;
        }
    }
    Apesblog.prototype.init.prototype =  Apesblog.prototype;
    window.apesblog = Apesblog;
})();