一直写代码写代码,博客都快荒废了,眼看一月要过完,不能不留下点记忆,嘿嘿,刚研究了下jquery的链式访问,这么好用的技能我赶紧get了下,研究后略微修改,模拟一个简单的链式访问,下面这段代码支持修改css,获取css属性值,显示和隐藏等小功能,打算抽空把自己的js小框架全改成链式访问。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="wmlink.js"></script> <style type="text/css"> #box { color: red; } </style> </head> <body> <div id="box">模拟链式访问</div> <div class="box">模拟链式访问</div> <div class="box">模拟链式访问</div> <div class="box">模拟链式访问</div> <script type="text/javascript"> (function(win){ var WM = function(selector) { this.element = [];//接收dom元素 return this.all(selector);// 返回id的dom元素 } var $ = function(selector) { return new WM(selector); } WM.prototype = { all:function(selector) { this.element = document.querySelectorAll(selector); return this; }, hide: function(){ for (var i = 0; i < this.element.length; i++) { this.element[i].style.display = 'none'; } return this; }, show: function(){ for (var i = 0; i < this.element.length; i++) { this.element[i].style.display = 'block'; } return this; }, css: function(key, value) { var doms = this.element; // 根据参数个数实现方法重载 if (doms.length) { for (var i = 0; i < doms.length; i++) { if (value) { this.setStyle(doms[i], key, value); } else { return this.getStyle(doms[0], key); } } } else { if (value) { this.setStyle(doms, key, value); } else { return this.getStyle(doms, key); } }; }, getStyle: function(dom, key) { if (dom.currentStyle) { return dom.currentStyle[key]; } else { return window.getComputedStyle(dom, null)[key]; } }, setStyle: function(dom, key, value) { dom.style[key] = value; }, } var demo =$('#box').css('color'); // 通过对象的引用调用 console.log(demo);// 获得属性值 $('.box').css('color','yellow') })(window) </script> </body> </html>