js 實(shí)現(xiàn)css風(fēng)格選擇器(壓縮后2KB)
更新時(shí)間:2012年01月12日 11:49:27 作者:
近日在做一些OA前端界面,為了更好管理頁(yè)面代碼想寫(xiě)個(gè)js選擇器,寫(xiě)著寫(xiě)著發(fā)現(xiàn)很費(fèi)力,索性在網(wǎng)上找找看,功夫不負(fù)有心人, 找到一個(gè)mini css選擇器,且性能不凡:以下代碼是壓縮后的,僅2KB
近日在做一些OA前端界面,為了更好管理頁(yè)面代碼想寫(xiě)個(gè)js選擇器,寫(xiě)著寫(xiě)著發(fā)現(xiàn)很費(fèi)力,索性在網(wǎng)上找找看,功夫不負(fù)有心人, 找到一個(gè)mini css選擇器,且性能不凡:以下代碼是壓縮后的,僅2KB。
var $=(function(){var b=/(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,g=/^(?:[\w\-_]+)?\.([\w\-_]+)/,f=/^(?:[\w\-_]+)?#([\w\-_]+)/,j=/^([\w\*\-_]+)/,h=[null,null];function d(o,m){m=m||document;var k=/^[\w\-_#]+$/.test(o);if(!k&&m.querySelectorAll){return c(m.querySelectorAll(o))}if(o.indexOf(",")>-1){var v=o.split(/,/g),t=[],s=0,r=v.length;for(;s<r;++s){t=t.concat(d(v[s],m))}return e(t)}var p=o.match(b),n=p.pop(),l=(n.match(f)||h)[1],u=!l&&(n.match(g)||h)[1],w=!l&&(n.match(j)||h)[1],q;if(u&&!w&&m.getElementsByClassName){q=c(m.getElementsByClassName(u))}else{q=!l&&c(m.getElementsByTagName(w||"*"));if(u){q=i(q,"className",RegExp("(^|\\s)"+u+"(\\s|$)"))}if(l){var x=m.getElementById(l);return x?[x]:[]}}return p[0]&&q[0]?a(p,q):q}function c(o){try{return Array.prototype.slice.call(o)}catch(n){var l=[],m=0,k=o.length;for(;m<k;++m){l[m]=o[m]}return l}}function a(w,p,n){var q=w.pop();if(q===">"){return a(w,p,true)}var s=[],k=-1,l=(q.match(f)||h)[1],t=!l&&(q.match(g)||h)[1],v=!l&&(q.match(j)||h)[1],u=-1,m,x,o;v=v&&v.toLowerCase();while((m=p[++u])){x=m.parentNode;do{o=!v||v==="*"||v===x.nodeName.toLowerCase();o=o&&(!l||x.id===l);o=o&&(!t||RegExp("(^|\\s)"+t+"(\\s|$)").test(x.className));if(n||o){break}}while((x=x.parentNode));if(o){s[++k]=m}}return w[0]&&s[0]?a(w,s):s}var e=(function(){var k=+new Date();var l=(function(){var m=1;return function(p){var o=p[k],n=m++;if(!o){p[k]=n;return true}return false}})();return function(m){var s=m.length,n=[],q=-1,o=0,p;for(;o<s;++o){p=m[o];if(l(p)){n[++q]=p}}k+=1;return n}})();function i(q,k,p){var m=-1,o,n=-1,l=[];while((o=q[++m])){if(p.test(o[k])){l[++n]=o}}return l}return d})();
把原版也分享下:
/**
* "mini" Selector Engine
* Copyright (c) 2009 James Padolsey
* -------------------------------------------------------
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
* -------------------------------------------------------
* Version: 0.01 (BETA)
*/
var mini = (function(){
var snack = /(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,
exprClassName = /^(?:[\w\-_]+)?\.([\w\-_]+)/,
exprId = /^(?:[\w\-_]+)?#([\w\-_]+)/,
exprNodeName = /^([\w\*\-_]+)/,
na = [null,null];
function _find(selector, context) {
/**
* This is what you call via x() 這是你們所謂的經(jīng)x
* Starts everything off... 開(kāi)始上所有的
*/
context = context || document;
var simple = /^[\w\-_#]+$/.test(selector);
if (!simple && context.querySelectorAll) {
return realArray(context.querySelectorAll(selector));
}
if (selector.indexOf(',') > -1) {
var split = selector.split(/,/g), ret = [], sIndex = 0, len = split.length;
for(; sIndex < len; ++sIndex) {
ret = ret.concat( _find(split[sIndex], context) );
}
return unique(ret);
}
var parts = selector.match(snack),
part = parts.pop(),
id = (part.match(exprId) || na)[1],
className = !id && (part.match(exprClassName) || na)[1],
nodeName = !id && (part.match(exprNodeName) || na)[1],
collection;
if (className && !nodeName && context.getElementsByClassName) {
collection = realArray(context.getElementsByClassName(className));
} else {
collection = !id && realArray(context.getElementsByTagName(nodeName || '*'));
if (className) {
collection = filterByAttr(collection, 'className', RegExp('(^|\\s)' + className + '(\\s|$)'));
}
if (id) {
var byId = context.getElementById(id);
return byId?[byId]:[];
}
}
return parts[0] && collection[0] ? filterParents(parts, collection) : collection;
}
function realArray(c) {
/**
* Transforms a node collection into 轉(zhuǎn)換一個(gè)節(jié)點(diǎn)收藏
* a real array 一個(gè)真正的陣列
*/
try {
return Array.prototype.slice.call(c);
} catch(e) {
var ret = [], i = 0, len = c.length;
for (; i < len; ++i) {
ret[i] = c[i];
}
return ret;
}
}
function filterParents(selectorParts, collection, direct) {
/**
* This is where the magic happens. 這就是魔法發(fā)生
* Parents are stepped through (upwards) to 父母?jìng)兗泳o通過(guò)向上
* see if they comply with the selector. 看看他們是否符合選擇器
*/
var parentSelector = selectorParts.pop();
if (parentSelector === '>') {
return filterParents(selectorParts, collection, true);
}
var ret = [],
r = -1,
id = (parentSelector.match(exprId) || na)[1],
className = !id && (parentSelector.match(exprClassName) || na)[1],
nodeName = !id && (parentSelector.match(exprNodeName) || na)[1],
cIndex = -1,
node, parent,
matches;
nodeName = nodeName && nodeName.toLowerCase();
while ( (node = collection[++cIndex]) ) {
parent = node.parentNode;
do {
matches = !nodeName || nodeName === '*' || nodeName === parent.nodeName.toLowerCase();
matches = matches && (!id || parent.id === id);
matches = matches && (!className || RegExp('(^|\\s)' + className + '(\\s|$)').test(parent.className));
if (direct || matches) { break; }
} while ( (parent = parent.parentNode) );
if (matches) {
ret[++r] = node;
}
}
return selectorParts[0] && ret[0] ? filterParents(selectorParts, ret) : ret;
}
var unique = (function(){
var uid = +new Date();
var data = (function(){
var n = 1;
return function(elem) {
var cacheIndex = elem[uid],
nextCacheIndex = n++;
if(!cacheIndex) {
elem[uid] = nextCacheIndex;
return true;
}
return false;
};
})();
return function(arr) {
/**
* Returns a unique array返回一個(gè)獨(dú)特的陣列
*/
var length = arr.length,
ret = [],
r = -1,
i = 0,
item;
for (; i < length; ++i) {
item = arr[i];
if (data(item)) {
ret[++r] = item;
}
}
uid += 1;
return ret;
};
})();
function filterByAttr(collection, attr, regex) {
/**
* Filters a collection by an attribute. 一個(gè)收集過(guò)濾器一個(gè)屬性
*/
var i = -1, node, r = -1, ret = [];
while ( (node = collection[++i]) ) {
if (regex.test(node[attr])) {
ret[++r] = node;
}
}
return ret;
}
return _find;
})();
以上代碼支持css風(fēng)格樣式寫(xiě)法包括:
div
.example
body div
div, p
div, p, .example
div p
div > p
div.example
ul .example
#title
h1#title
div #title
ul.foo > * span
復(fù)制代碼 代碼如下:
var $=(function(){var b=/(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,g=/^(?:[\w\-_]+)?\.([\w\-_]+)/,f=/^(?:[\w\-_]+)?#([\w\-_]+)/,j=/^([\w\*\-_]+)/,h=[null,null];function d(o,m){m=m||document;var k=/^[\w\-_#]+$/.test(o);if(!k&&m.querySelectorAll){return c(m.querySelectorAll(o))}if(o.indexOf(",")>-1){var v=o.split(/,/g),t=[],s=0,r=v.length;for(;s<r;++s){t=t.concat(d(v[s],m))}return e(t)}var p=o.match(b),n=p.pop(),l=(n.match(f)||h)[1],u=!l&&(n.match(g)||h)[1],w=!l&&(n.match(j)||h)[1],q;if(u&&!w&&m.getElementsByClassName){q=c(m.getElementsByClassName(u))}else{q=!l&&c(m.getElementsByTagName(w||"*"));if(u){q=i(q,"className",RegExp("(^|\\s)"+u+"(\\s|$)"))}if(l){var x=m.getElementById(l);return x?[x]:[]}}return p[0]&&q[0]?a(p,q):q}function c(o){try{return Array.prototype.slice.call(o)}catch(n){var l=[],m=0,k=o.length;for(;m<k;++m){l[m]=o[m]}return l}}function a(w,p,n){var q=w.pop();if(q===">"){return a(w,p,true)}var s=[],k=-1,l=(q.match(f)||h)[1],t=!l&&(q.match(g)||h)[1],v=!l&&(q.match(j)||h)[1],u=-1,m,x,o;v=v&&v.toLowerCase();while((m=p[++u])){x=m.parentNode;do{o=!v||v==="*"||v===x.nodeName.toLowerCase();o=o&&(!l||x.id===l);o=o&&(!t||RegExp("(^|\\s)"+t+"(\\s|$)").test(x.className));if(n||o){break}}while((x=x.parentNode));if(o){s[++k]=m}}return w[0]&&s[0]?a(w,s):s}var e=(function(){var k=+new Date();var l=(function(){var m=1;return function(p){var o=p[k],n=m++;if(!o){p[k]=n;return true}return false}})();return function(m){var s=m.length,n=[],q=-1,o=0,p;for(;o<s;++o){p=m[o];if(l(p)){n[++q]=p}}k+=1;return n}})();function i(q,k,p){var m=-1,o,n=-1,l=[];while((o=q[++m])){if(p.test(o[k])){l[++n]=o}}return l}return d})();
把原版也分享下:
復(fù)制代碼 代碼如下:
/**
* "mini" Selector Engine
* Copyright (c) 2009 James Padolsey
* -------------------------------------------------------
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
* -------------------------------------------------------
* Version: 0.01 (BETA)
*/
var mini = (function(){
var snack = /(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig,
exprClassName = /^(?:[\w\-_]+)?\.([\w\-_]+)/,
exprId = /^(?:[\w\-_]+)?#([\w\-_]+)/,
exprNodeName = /^([\w\*\-_]+)/,
na = [null,null];
function _find(selector, context) {
/**
* This is what you call via x() 這是你們所謂的經(jīng)x
* Starts everything off... 開(kāi)始上所有的
*/
context = context || document;
var simple = /^[\w\-_#]+$/.test(selector);
if (!simple && context.querySelectorAll) {
return realArray(context.querySelectorAll(selector));
}
if (selector.indexOf(',') > -1) {
var split = selector.split(/,/g), ret = [], sIndex = 0, len = split.length;
for(; sIndex < len; ++sIndex) {
ret = ret.concat( _find(split[sIndex], context) );
}
return unique(ret);
}
var parts = selector.match(snack),
part = parts.pop(),
id = (part.match(exprId) || na)[1],
className = !id && (part.match(exprClassName) || na)[1],
nodeName = !id && (part.match(exprNodeName) || na)[1],
collection;
if (className && !nodeName && context.getElementsByClassName) {
collection = realArray(context.getElementsByClassName(className));
} else {
collection = !id && realArray(context.getElementsByTagName(nodeName || '*'));
if (className) {
collection = filterByAttr(collection, 'className', RegExp('(^|\\s)' + className + '(\\s|$)'));
}
if (id) {
var byId = context.getElementById(id);
return byId?[byId]:[];
}
}
return parts[0] && collection[0] ? filterParents(parts, collection) : collection;
}
function realArray(c) {
/**
* Transforms a node collection into 轉(zhuǎn)換一個(gè)節(jié)點(diǎn)收藏
* a real array 一個(gè)真正的陣列
*/
try {
return Array.prototype.slice.call(c);
} catch(e) {
var ret = [], i = 0, len = c.length;
for (; i < len; ++i) {
ret[i] = c[i];
}
return ret;
}
}
function filterParents(selectorParts, collection, direct) {
/**
* This is where the magic happens. 這就是魔法發(fā)生
* Parents are stepped through (upwards) to 父母?jìng)兗泳o通過(guò)向上
* see if they comply with the selector. 看看他們是否符合選擇器
*/
var parentSelector = selectorParts.pop();
if (parentSelector === '>') {
return filterParents(selectorParts, collection, true);
}
var ret = [],
r = -1,
id = (parentSelector.match(exprId) || na)[1],
className = !id && (parentSelector.match(exprClassName) || na)[1],
nodeName = !id && (parentSelector.match(exprNodeName) || na)[1],
cIndex = -1,
node, parent,
matches;
nodeName = nodeName && nodeName.toLowerCase();
while ( (node = collection[++cIndex]) ) {
parent = node.parentNode;
do {
matches = !nodeName || nodeName === '*' || nodeName === parent.nodeName.toLowerCase();
matches = matches && (!id || parent.id === id);
matches = matches && (!className || RegExp('(^|\\s)' + className + '(\\s|$)').test(parent.className));
if (direct || matches) { break; }
} while ( (parent = parent.parentNode) );
if (matches) {
ret[++r] = node;
}
}
return selectorParts[0] && ret[0] ? filterParents(selectorParts, ret) : ret;
}
var unique = (function(){
var uid = +new Date();
var data = (function(){
var n = 1;
return function(elem) {
var cacheIndex = elem[uid],
nextCacheIndex = n++;
if(!cacheIndex) {
elem[uid] = nextCacheIndex;
return true;
}
return false;
};
})();
return function(arr) {
/**
* Returns a unique array返回一個(gè)獨(dú)特的陣列
*/
var length = arr.length,
ret = [],
r = -1,
i = 0,
item;
for (; i < length; ++i) {
item = arr[i];
if (data(item)) {
ret[++r] = item;
}
}
uid += 1;
return ret;
};
})();
function filterByAttr(collection, attr, regex) {
/**
* Filters a collection by an attribute. 一個(gè)收集過(guò)濾器一個(gè)屬性
*/
var i = -1, node, r = -1, ret = [];
while ( (node = collection[++i]) ) {
if (regex.test(node[attr])) {
ret[++r] = node;
}
}
return ret;
}
return _find;
})();
以上代碼支持css風(fēng)格樣式寫(xiě)法包括:
復(fù)制代碼 代碼如下:
div
.example
body div
div, p
div, p, .example
div p
div > p
div.example
ul .example
#title
h1#title
div #title
ul.foo > * span
您可能感興趣的文章:
- 高性能WEB開(kāi)發(fā) JS、CSS的合并、壓縮、緩存管理
- 一款JavaScript壓縮工具:X2JSCompactor
- php實(shí)現(xiàn)壓縮多個(gè)CSS與JS文件的方法
- IIS7下js文件啟用Gzip后卻不壓縮的解決方法
- css js 圖片壓縮批處理命令(基于YUI Compressor)
- JavaScript(JS) 壓縮 / 混淆 / 格式化 批處理工具
- asp.net C#實(shí)現(xiàn)解壓縮文件的方法
- asp.net(C#)壓縮圖片,可以指定圖片模板高寬
- asp.net中調(diào)用winrar實(shí)現(xiàn)壓縮解壓縮的代碼
- Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法
相關(guān)文章
JS實(shí)現(xiàn)手寫(xiě)parseInt的方法示例
這篇文章主要給大家介紹了JS實(shí)現(xiàn)手寫(xiě)parseInt的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09JS?中的類Public,Private?和?Protected詳解
這篇文章主要介紹了JS中的類Public,Private和Protected詳解,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08解讀new?Object()和Object.create()的區(qū)別
這篇文章主要介紹了解讀new?Object()和Object.create()的區(qū)別及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02js遍歷對(duì)象key和value實(shí)戰(zhàn)舉例
這篇文章主要給大家介紹了關(guān)于js遍歷對(duì)象key和value的相關(guān)資料,隨著JavaScript在web應(yīng)用程序中的廣泛使用,遍歷對(duì)象的key和value成為了編寫(xiě)復(fù)雜代碼所必需的技能,需要的朋友可以參考下2023-07-07JavaScript中利用Array和Object實(shí)現(xiàn)Map的方法
這篇文章主要介紹了JavaScript中利用Array和Object實(shí)現(xiàn)Map的方法,實(shí)例分析了javascript實(shí)現(xiàn)map的添加、獲取、移除、清空、遍歷等操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07Js中將Long轉(zhuǎn)換成日期格式的實(shí)現(xiàn)方法
這篇文章主要介紹了Js中將Long轉(zhuǎn)換成日期格式的實(shí)現(xiàn)方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06Three.Js實(shí)現(xiàn)看房自由小項(xiàng)目
目前隨著元宇宙概念的爆火,THREE技術(shù)已經(jīng)深入到了物聯(lián)網(wǎng)、VR、游戲、數(shù)據(jù)可視化等多個(gè)平臺(tái),今天我們主要基于THREE實(shí)現(xiàn)一個(gè)三維的VR看房小項(xiàng)目,感興趣的朋友跟隨小編一起看看吧2022-10-10