我想通过 document.styleSheets 获取样式表,但是,Firefox 似乎会默默地忽略一些不非法的 CSS 值。我现在正在使用vh & vw,我想获取 css 值并为其生成正确的 px 。
有什么方法可以让 Firefox 忽略这些值?
我想通过 document.styleSheets 获取样式表,但是,Firefox 似乎会默默地忽略一些不非法的 CSS 值。我现在正在使用vh & vw,我想获取 css 值并为其生成正确的 px 。
有什么方法可以让 Firefox 忽略这些值?
我确实认为 Firefox(可能还有其他浏览器)只会从样式表中返回计算出的样式。
但是,您可以通过选择所需的标签进入更手动的过程,发出 ajax 请求以获取其文本内容(几乎是即时的,因为它在缓存中),然后解析它。
html:
<link rel="stylesheet" href="style.css" id="css">
js(使用 jQuery):
$.get($("#css").attr("href"), function(data) //requests the css in ajax
{
var selector = "div#right", rules = {};
data = data.substring(data.indexOf(selector)); //trim all that is before your selector
data = data.substring(data.indexOf("{") + 1, data.indexOf("}")); //get only what's in the curly braces
data = data.split(";"); //split to get an array with each cell is a css rule
for (var i = 0, l = data.length; i < l; i++) //loop through
{
data[i] = data[i].replace(/^\s+/, ''); //trim spaces before
data[i] = data[i].replace(/\s+$/, ''); //trim spaces after
if (data[i].indexOf(':') == -1) { continue; } //if rule is invalid, skip it
data[i] = data[i].split(':'); //split rule so you have a sub-array with 0:key and 1:value
rules[data[i][0]] = data[i][1]; //apply it to an object
}
console.dir(rules); //here you have. if your rules have "-" in it, you can't access with directly, but with brackets it'll be ok. ie : rules.margin-left is wrong but you can with rules["margin-left"].
}, "text");