So I am looking for a jQuery Plugin or a method using javascript in general where I can obtain CSS properties from a string without using a lot of If else statements I have to write. The string comes from a user input like a Text area. Example:
var string = "#hello{border:1px #000 solid;background-color:#FFF;}";
So basically I want to be able to identify ID's and Classes from a string and their properties. So in this case that there is an ID called Hello and that it has a 1px border and a background color of #FFF (white). The info will be then be added to an object asnd pushed into an array. Is t开发者_如何学运维here a plugin or a way I can do this? There will also be multiple in each string. I know this might seem a little confusing. Thanks!
It seems that you want to parse CSS style rules and extract the components. That isn't too hard since the general syntax is a selector followed by a list of zero or more semi-colon separated sets of colon separated name:value pairs (i.e. selector { property : value; property : value; …}).
A regular expression should do the trick, however it might get complex if you want the selector to be fully compliant with the current standard, CSS 2.1.
If all you want is single id and class selectors, then life is much simpler. A start on such a function is:
function parseCSSRule(s) {
var a = s.indexOf('{');
var b = s.indexOf('}');
var selector = s.substring(0, a);
var rules = s.substring(++a, b).split(';');
// Do something with the selector and the rules
alert(selector + '\n' + rules);
}
that will split the selector from the rules, then separate the rules into an array. You will need to deal with a bit of whitespace here and there, but otherwise if all you want to do is apply the (possibly empty set of) style rules to an element selected by the selector, that's about it.
You just need to split each rule on the colon ":" and apply the CSS text to the appropriate style property, changing hyphenated names to camelCase in the processs.
Edit
Oh, and if you want a really simple solution, just add the rule to the bottom of the last style sheet in the document. That way you don't have to parse it at all, just drop it in and let the browser do the work.
This can be quite trivial if you run javascript on the rendered page. First, get a list of all CSS properties (the list can be quite large).
Then you do: (pseudocode)
var properties = []
foreach(property in css_properies)
{
var value = $('#hello').css(property)
if( value != "" )
properites.push(property + ':' + value)
}
Then the string you want would become:
'#hello{' + properties.join(';') + '}'
Now, the list contains all computed styles, so it can be quite large. See the css method for more details.
JSCSSP is a CSS parser that I believe should be able to do exactly what you are looking for. Please look at the following link:
http://glazman.org/JSCSSP/
Please tell me if it looks like an appropriate solution to you. Thanks.
精彩评论