使用 getComputedStyle(elem, false)['borderWidth'] 在 Firefox 中回傳異常值(如 medium 或空字串),而在 IE/Chrome 正常回傳像素值(如 "2px")。
borderWidth 是 簡寫屬性(Shorthand Property)。CSSOM 規範規定:getComputedStyle 對簡寫屬性的回傳值 未標準化,各瀏覽器實現不同:
"2px"),不同則回傳空字串。medium、thin、thick 或空字串。currentStyle['borderWidth'] 回傳像素值。改用具體方向的長屬性,確保跨瀏覽器一致回傳 "2px" 格式:
function getBorderWidth(elem, side) {
// side: 'Top' | 'Right' | 'Bottom' | 'Left'
const prop = 'border' + side + 'Width';
if (window.getComputedStyle) {
return getComputedStyle(elem, null)[prop];
} else if (elem.currentStyle) { // IE8-
return elem.currentStyle[prop];
}
return '0px';
}
// 使用範例
const leftWidth = getBorderWidth(div, 'Left'); // 回傳 "2px"
原代碼嘗試對 borderWidth 做動畫(startMove(this,'borderWidth',14))。建議:
borderLeftWidth 等單邊,視覺效果相近但可控。parseFloat(getBorderWidth(...)) 取得數字。<div id="div4" style="border: 2px solid red; width:100px; height:100px;"></div>
<script>
function getStyle(obj, name) {
if (obj.currentStyle) return obj.currentStyle[name];
return getComputedStyle(obj, false)[name];
}
window.onload = function() {
const d = document.getElementById('div4');
console.log('borderWidth (shorthand):', getStyle(d, 'borderWidth')); // Firefox: "medium"
console.log('borderLeftWidth (longhand):', getStyle(d, 'borderLeftWidth')); // 所有瀏覽器: "2px"
};
</script>
CSS 簡寫屬性在 getComputedStyle 中行為不可靠。開發動畫、樣式讀取工具時,務必使用長屬性(如 borderLeftWidth、marginTop、paddingRight)以保證跨瀏覽器一致性。