在 Javascript 中我们可以使用像 window.getComputedStyle(element,null).getPropertyValue(property)
这样的东西检索给定元素的样式属性。也就是说,任何属性都可以通过响应式网页设计在任何屏幕尺寸下发生变化。
我想知道是否可以分析元素的相关样式表以确定将在所有窗口大小/断点处应用到它的样式。
例如,<p>
有font-size: 16px
在桌面上,和 font-size: 18px
在移动设备上(由 @media (max-width: 768px) { ... }
设置。我想知道移动设备上的字体大小将为 18px,而无需调整为移动设备大小并再次对字体大小进行采样。
我想通过在 JS 中进行一些巧妙的文本处理,我可以对 @media
的样式表进行排序。并查看它是否反射(reflect)在元素上,但对于更大或多个样式表、内联样式和注入(inject)样式,该方法可能无法获得 100% 的准确度。
有什么想法吗?
思想...
是否可以将元素包装在模拟(隐藏)中 window
元素然后使用 JS 调整它的大小以触发媒体查询?
另一种方法...
我开始研究 document.styleSheets
但即便如此,要做到完美似乎也是一项几乎不可能完成的任务。在下面的示例中,我将一些选定的文本包装在一个元素中,然后将其传递给下面的方法(用 coffeescript 编写)。
analyzeSelectiontyles: (selectionElement) ->
selectionParents = []
while selectionElement
selectionParents.unshift selectionElement
selectionElement = selectionElement.parentNode
pageStylesheets = document.styleSheets
for stylesheet in pageStylesheets
rules = stylesheet.cssRules
for rule of rules
if rules[rule]["type"] is 1
console.log 'standard style'
if rules[rule]["type"] is 4
console.log 'media query'
# If it's a standard style rule or a media query containing
# style rules we have to check to see if the style rule applies
# to any one of our selectionParents defined above, and in
# Which order so as to simulate "cascading"
最佳答案
像下面这样的东西可能会起作用当场所有样式都托管在 same origin 上.我这里测试了,获取不到all.css
文件;我假设是因为它托管在不同的 cdn 域上。
function css(element) {
var sheets = document.styleSheets,
standard = [],
mediaStyles = {};
element.matches = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || element.oMatchesSelector;
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (element.matches(rules[r].selectorText)) {
if (rules[r]["type"] === 4) {
mediaStyles[rules[r].media] = (mediaStyles[rules[r].media] || []).push(rules[r].cssText);
} else {
standard.push(rules[r].cssText);
}
}
}
}
return { 'standard': standard, 'media': mediaStyles };
}
关于javascript - 确定所有屏幕尺寸的元素样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27540082/