我正在使用 window.getComputedStyle()
来获取属性的 CSS 值:
- 边框半径
- 边框样式
- 边框宽度
- 边框颜色
我注意到最新的 FF 会返回空字符串,而 Chrome 会返回带有单位的计算值:
FF:
"borderRadius":"","borderStyle":"","borderWidth":"","borderColor":""
Chrome :
"borderRadius":"0px","borderStyle":"none","borderWidth":"0px","borderColor":"rgb(0, 0, 0)"}
我想知道:
- 这种差异是由已知错误引起的吗?
- 您知道强制 FF 像 Chrome 一样返回值的方法吗? (我知道我可以在某些条件下添加默认值,但如果可能的话我会使用 native 解决方案)。
(function (window) {
document.addEventListener('DOMContentLoaded', (event) => {
let elmTarget = document.querySelector('#target'),
elmResult = document.querySelector('#result');
let styles = window.getComputedStyle(elmTarget),
result = {
borderRadius: styles.borderRadius,
borderStyle: styles.borderStyle,
borderWidth: styles.borderWidth,
borderColor: styles.borderColor
},
resultStr = JSON.stringify(result);
console.log(resultStr);
elmResult.innerHTML = resultStr;
});
})(window);
#target {
background-color: blue;
width: 100px;
height: 50px;
}
<div id="target"></div>
<div id="result"></div>
最佳答案
简写。
在 FF 中你需要单独获取所有内容。
border-left-style
border-top-style
border-bottom-style
border-right-style
border-left-width
...
border-radius
更长:
border-top-left-radius
border-top-right-radius
...
(function(window) {
document.addEventListener('DOMContentLoaded', (event) => {
let elmTarget = document.querySelector('#target'),
elmResult = document.querySelector('#result');
let styles = window.getComputedStyle(elmTarget),
result = {
borderTopLeftRadius: styles.borderTopLeftRadius,
borderTopRightRadius: styles.borderTopRightRadius,
borderBottomLeftRadius: styles.borderBottomLeftRadius,
borderBottomRightRadius: styles.borderBottomRightRadius,
borderLeftStyle: styles.borderLeftStyle,
borderTopStyle: styles.borderTopStyle,
borderBottomStyle: styles.borderBottomStyle,
borderRightStyle: styles.borderRightStyle,
borderLeftWidth: styles.borderLeftWidth,
borderTopWidth: styles.borderTopWidth,
borderRightWidth: styles.borderRightWidth,
borderBottomWidth: styles.borderBottomWidth,
borderLeftColor: styles.borderLeftColor,
borderTopColor: styles.borderTopColor,
borderBottomColor: styles.borderBottomColor,
borderRightColor: styles.borderRightColor,
},
resultStr = JSON.stringify(result);
console.log(resultStr);
elmResult.innerHTML = resultStr;
});
})(window);
#target {
background-color: blue;
width: 100px;
height: 50px;
}
<div id="target"></div>
<div id="result"></div>
关于javascript - getComputedStyle() 在 FF 上返回空字符串,而 Crome 返回一个计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41696063/