国产探花免费观看_亚洲丰满少妇自慰呻吟_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先不管

主站蜘蛛池模板: 北流市| 海原县| 芮城县| 自治县| 开江县| 尚义县| 肥城市| 西平县| 开江县| 鄂尔多斯市| 美姑县| 新泰市| 辽宁省| 南川市| 南汇区| 三台县| 榆林市| 炉霍县| 罗定市| 陕西省| 辽源市| 忻城县| 昌平区| 海林市| 灯塔市| 溧阳市| 当雄县| 铁岭市| 富蕴县| 宣威市| 龙游县| 保康县| 三河市| 彭阳县| 田东县| 夏津县| 陵水| 黔西县| 甘德县| 略阳县| 巴彦淖尔市|