有没有办法使用 javascript 获取这些样式
window.getComputedStyle()
返回所有内容,包括默认值。
我需要获取我选择的元素的所有 css,每个样式规则包括它从其父元素继承的样式。
开发工具的基本功能。
最佳答案
function getFileStyle(ele) {
var styleSheets = document.styleSheets
return Array.from(styleSheets).reduce((re, sheet) => {
if (sheet.cssRules !== null) {
var href = sheet.href
Array.from(sheet.cssRules).reduce((r, rule) => {
var selector = rule.selectorText
if (Array.from(document.querySelectorAll(selector)).includes(ele)) {
r[selector] = r[selector]
? [...r[selector], { css: rule.style.cssText, href }]
: [{ css: rule.style.cssText, href }]
}
return r
}, re)
}
return re
}, {})
}
console.log(getFileStyle(document.body))
1、但是,如果您在该页面上运行代码,您将什么也得不到,因为所使用的 SO 样式来自不同的域。
In some browsers, if a stylesheet is loaded from a different domain, calling cssRules results in SecurityError.
2、你的问题不清楚,因为你应该给我们一个预期的输出而不是图像。图像只显示适用的样式规则,而适用的样式规则在某些情况下会发生变化。
例如,如果您像在移动设备上一样将窗口大小调整为 300*300。您看到的样式可能会发生变化,因为其他样式规则可能适用。
所以,我的代码不能给你实时适用的规则,很麻烦。
3、在大多数情况下,getComputedStyle
就足够了。如果您必须处理styleSheets
,我认为总有另一种简单的方法。
关于javascript - 如何获取特定元素的用户样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890354/