国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

jQuery鏈式調用與show知識淺析

2019-11-20 10:06:24
字體:
來源:轉載
供稿:網友

上篇文章給大家介紹了jQuery的框架,有關jquery的基礎知識可以參考下。

jQuery使用許久了,但是有一些API的實現實在想不通。下面將使用簡化的代碼來介紹,主要關注jQuery的實現思想。

相較于上一篇,代碼更新了:21~78

(function(window, undefined){function jQuery(sel){return new jQuery.prototype.init(sel);}jQuery.prototype = {constructor: jQuery,init: function(sel){if(typeof sel === 'string'){var that = this;var nodeList = document.querySelectorAll(sel);Array.prototype.forEach.call(nodeList, function(val, i){that[i] = val;})this.selector = sel;this.length = nodeList.length;}},show: function(){Array.prototype.forEach.call(this, function(node){//if(node.style) continue; //textnode沒有style//刪除style上的display:nonevar display = node.style.display;if(display === 'none'){//dispaly置為空后,css如果有display則css的生效//否則默認的生效node.style.display = '';}//元素display值為非默認值情況,需要還原為oldDisplay:div->display:inline-block//或 檢測css上的display是否為noneif(node.style.display==='' || isHidden(node)){//有oldDispaly則設置if(node.oldDisplay) node.style.display = node.oldDisplay;//沒有則設置為元素默認值或元素當前值else node.style.display = getDisplay(node);}})//鏈式調用return this;},hide: function(){Array.prototype.forEach.call(this, function(node){if(!isHidden(node)) {//jQuery使用其cache機制存儲信息,這里簡化一下//直接掛載在對應的dom下node.oldDisplay = getDisplay(node);node.style.display = 'none';}})return this;}}function getDisplay(node){var display = window.getComputedStyle(node, null).getPropertyValue('display');if(display === 'none'){var dom = document.createElement(node.nodeName);//插入到body中document.body.appendChild(dom);//即可獲取到元素display的默認值var display = window.getComputedStyle(dom, null).getPropertyValue('display');document.body.removeChild(dom);}return display;}function isHidden(node) {//忽略未append進document的元素這種隱藏情況:$('<div>block</div>')未appendreturn window.getComputedStyle(node, null).getPropertyValue('display') === 'none';}jQuery.prototype.init.prototype = jQuery.prototype;window.$ = jQuery;})(window); 

先拿hide函數熱身一下。如上篇提到的,jQuery會將獲取到的nodeList處理成數組,所以一上來,我們用forEach處理數組里的每一個node節點。

接下來,我們只需要將每一個節點的style.display置為'none'即可隱藏。很簡單,對吧?(⊙0⊙) 。oldDisplay和return this先不管

主站蜘蛛池模板: 文水县| 体育| 德清县| 云安县| 台前县| 金山区| 伊宁市| 全南县| 溧水县| 石狮市| 鸡东县| 邹平县| 桂东县| 浦县| 正宁县| 安吉县| 岐山县| 宜州市| 平潭县| 娱乐| 涡阳县| 青河县| 临桂县| 万年县| 会泽县| 峨山| 拜泉县| 湘潭市| 华坪县| 海丰县| 岑巩县| 安龙县| 岳池县| 阿坝县| 岳池县| 青冈县| 伊宁市| 普洱| 安仁县| 扎鲁特旗| 永州市|