gpt4 book ai didi

javascript - 有什么方法可以选择DOM中不存在的带有JS的CSS类吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:16 25 4
gpt4 key购买 nike

是否可以选择一个 CSS class with JS,它只在其文件中注册,不存在于 DOM 中?

var elem = document.getElementsByClassName('class2')[0],
getStyle = window.getComputedStyle(elem),
value = getStyle.getPropertyValue('top');
console.log(value);
// Can't get the value of class2 because it doesn't exist in DOM.
.class1 {
top: 10px;
}
.class2 {
top: 20px;
}
<div class="class1">
top
</div>

像这个例子,选择 .class1 没有问题,因为它存在于元素中的 DOM 中。

但是我想访问 DOM 中不存在的 .class2

有没有办法做到这一点?

最佳答案

XY 问题在这里......你不是想要得到一个元素,而是在样式表中设置的值。

即使这可能是可能的(它是,但非常复杂),但该方法存在一个很大的缺陷:因为存在 CSS 规则并不意味着它会被应用。。。 p>

例如在您的情况下,.class2 规则确实存在并且处于事件状态,但是,由于没有元素匹配此规则,因此它不会产生任何影响。
同样,即使一个元素确实匹配这条规则,它也很可能被其他规则覆盖:

console.log(
getComputedStyle(
document.querySelector('.class2')
).getPropertyValue('top')
); // "10px"
#foo { top: 10px };
.class2 { top: 50px; }
<div class="class2" id="foo"></div>

所以,是的,您可以获得 CSSRule 的设置值:

const matching_rules = [...document.styleSheets].reduce((matched, sheet) => {
[...sheet.cssRules].forEach( r => {
if(r.selectorText && r.selectorText.includes('.class2'))
matched.push(r.style.top);
});
return matched;
}, []);
console.log(matching_rules);
.class2 { top: 50px; }

但再一次,这真的没有用,大多数时候,你只需要在你的元素附加到 DOM 后调用 getComputedStyle(之前调用它是没有用的,因为没有 CSS 规则应用于未显示的元素。

const elem = document.createElement('div');
elem.classList.add('class2');
console.log('matches:', elem.matches('.class2')); // true
const comp = getComputedStyle(elem);
console.log('computed top:', JSON.stringify(comp.getPropertyValue('top'))); // "" (the default)
.class2 {
top: 50px;
}

关于javascript - 有什么方法可以选择DOM中不存在的带有JS的CSS类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com