我有css后面的…
<style>
.body{
width:2px;
height:3px;
}
</style>
<style>
.anotherOne{
key:value;
...........
}
</style>
和HTML部分
<div class="body"></div>
那么我怎样才能在第一个样式标签上获得'body'类中的值呢?我也想在那里追加数据,我怎么能做这个javascript和正则表达式??还有别的办法吗?
我想把里面所有以".body{" and ending with "}"
width:2px;
height:3px;
如果你在javascript字符串中有单独的CSS样式,你可以使用这个正则表达式获得宽度值:
var re = /'.body's*'{[^'}]*?width's*:'s*(.*);/m;
var matches = str.match(re);
if (matches) {
var width = matches[1];
}
测试用例:http://jsfiddle.net/jfriend00/jSDeJ/.
高度值可以通过以下regex获得:
'.body's*'{[^'}]*?height's*:'s*(.*);/m;
如果你只想要正文标签的文本(不管它是什么)那么你可以这样做:
var re = /'.body's*'{([^'}]*?)'}/m;
var matches = str.match(re);
if (matches) {
var width = matches[1];
}
您可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/jSDeJ/3/
如果你想用你自己的字符串替换整个。body样式,你可以这样做:
var str = " <style>'n.body{'n width:2px; 'n height:3px; 'n } 'n</style>";
var re = /('.body's*'{)([^'}]*?)('})/m;
var newStyle = "width: 20px; 'nheight: 1000px;";
var result = str.replace(re, "$1" + newStyle + "$3");
alert(result);
你可以看到这里的工作:http://jsfiddle.net/jfriend00/jSDeJ/8/
看起来很有希望…
https://github.com/sabberworm/PHP-CSS-Parser或者,如果你只是想知道"计算值",我将依赖于浏览器的解析器,只是用javascript DOM方法提取值。