0
我想通過document.styleSheets獲取樣式表,但是,似乎Firefox會默默地忽略一些CSS值,而這些CSS值不是非法的。我現在使用vh & vw,我想獲得css值併爲其生成正確的px。Firefox會默默地忽略一些CSS值,他們不是非法的
有什麼辦法讓Firefox忽略的值?
我想通過document.styleSheets獲取樣式表,但是,似乎Firefox會默默地忽略一些CSS值,而這些CSS值不是非法的。我現在使用vh & vw,我想獲得css值併爲其生成正確的px。Firefox會默默地忽略一些CSS值,他們不是非法的
有什麼辦法讓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");
非常感謝。 –
難道只是我,或者是這個問題有點模糊? –
向我們展示一個可重現的代碼示例。 – Brad
你能顯示你的代碼嗎? –