简体   繁体   English

如何使用JavaScript压缩CSS选择器字符串

[英]How to compress a CSS selector string, using javascript

Maybe there's a library that does this already? 也许已经有一个图书馆了吗? All I could find is online tools. 我所能找到的只是在线工具。 The reason I want to do this in javascript is because I want to know that the string a > b, a is the same as a> b,a . 我想在javascript中执行此操作的原因是因为我想知道字符串a > b, aa> b,a If I can compress it as CSS, all versions will end up as the same string. 如果我可以将其压缩为CSS,则所有版本都将以相同的字符串结尾。

A better explanation of why I'm trying to do this: I wrote a jQuery plugin for myself to cache jQuery selectors (this stuff $('div') ). 我为什么要这样做的一个更好的解释:我为自己写了一个jQuery插件来缓存jQuery选择器(这个东西$('div') )。 It works by storing a key value pair, where the key is my selector string, and the value is the DOM elements found. 它通过存储一个键值对来工作,其中键是我的选择器字符串,而值是找到的DOM元素。 This is why I'd like to compare CSS selector strings, otherwise I'd be storing different keys that are essentially the same selector. 这就是为什么我想比较CSS选择器字符串的原因,否则我将存储本质上是相同选择器的不同键。

Uglify.js (https://github.com/mishoo/UglifyJS) can let you automate compression of CSS. Uglify.js(https://github.com/mishoo/UglifyJS)可以让您自动压缩CSS。 It will strip out all unnecessary white spaces and comments. 它将去除所有不必要的空格和注释。 This should allow you to normalize whatever you want. 这应该使您可以标准化任何内容。 You will need to look at Uglify source and attempt to extract just the needed components. 您将需要查看Uglify的源并尝试仅提取所需的组件。

When I experimented on: http://refresh-sf.com/yui/ it seems the selector was always minified appropriately (although that was using YUI not uglifyjs). 当我尝试以下方法时: http ://refresh-sf.com/yui/似乎总是适当地缩小了选择器(尽管使用的是YUI而不是uglifyjs)。 The only remaining issue is the difference between a>b,b and b,a>b. 唯一剩下的问题是a> b,b和b,a> b之间的差异。 For that I would recommend first minifying then splitting by ','; 为此,我建议先缩小然后再用','分割; then sorting the array alphabetically; 然后按字母顺序对数组进行排序; and finally rejoining the split array. 最后重新加入拆分数组。 Once done you can use that value as the hash. 完成后,您可以将该值用作哈希值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM