有沒有什么快速的方法可以得到CSS值的公式,而不是它的計算版本?
也就是說,我試圖得到calc(100vh - 305px),但我得到的是計算結(jié)果;"542.984375px & quot。
我使用這段代碼來獲取Safari控制臺中的值:
window.getComputedStyle($0).getPropertyValue('height');
無需多想:
查找應(yīng)用于元素的CSS規(guī)則 根據(jù)特殊性對它們進(jìn)行分類https://stackoverflow.com/a/67144451/14098260 返回第一條規(guī)則
const width = findRule(document.querySelector('.test'), 'width');
console.log(width);
function findRule(elem, name) {
const found = [];
for (const {cssRules} of document.styleSheets) {
for (const {style, selectorText} of cssRules) {
const value = style?.[name];
value &&
elem.matches(selectorText) &&
found.push([selectorText, value]);
}
}
// sort by specificity
found.sort(([a], [b]) => {
const applied = compare(a, b);
return applied === a? -1: 1;
});
return found[0][1];
}
// https://stackoverflow.com/a/67144451/14098260
function compare(a, b) {
let aItems = a.split([" "]);
let aRating = [0, 0, 0];
aItems.forEach((i) => {
if (i.split("#").length > 1) {
aRating[0] = aRating[0] + (i.split("#").length - 1);
}
if (i.split(".").length > 1) {
aRating[1] = aRating[1] + (i.split(".").length - 1);
}
if (!i.startsWith("#") && !i.startsWith(".")) {
aRating[2] = aRating[2] + 1;
}
});
let bItems = b.split([" "]);
let bRating = [0, 0, 0];
bItems.forEach((i) => {
if (i.split("#").length > 1) {
bRating[0] = bRating[0] + (i.split("#").length - 1);
}
if (i.split(".").length > 1) {
bRating[1] = bRating[1] + (i.split(".").length - 1);
}
if (!i.startsWith("#") && !i.startsWith(".")) {
bRating[2] = bRating[2] + 1;
}
});
if (aRating[0] > bRating[0]) {
return a;
} else if (bRating[0] > aRating[0]) {
return b;
}
if (aRating[1] > bRating[1]) {
return a;
} else if (bRating[1] > aRating[1]) {
return b;
} else if (
bRating[0] === aRating[0] &&
bRating[2] === 0 &&
aRating[2] === 0
) {
return b;
}
if (aRating[2] > bRating[2]) {
return a;
} else if (bRating[2] > aRating[2]) {
return b;
}
}
div{
width: 100%;
border: 1px solit #777;
}
div.test{
width: calc(100vw - 100px);
}
.test{
background: #aaa;
width: 300px;
}
<div class='test'>Test</div>