使用 JavaScript 從 HTML 元素中擷取樣式值
取得 HTML 元素的樣式屬性對於動態操作其外觀至關重要。本文深入研究了使用純 JavaScript 檢索樣式值而不借助任何外部程式庫的細微差別。
CurrentStyle 與計算屬性
要存取樣式值,我們需要區分內聯樣式(在元素的樣式屬性中定義)和計算屬性(實際應用的樣式)。
Internet Explorer使用 element.currentStyle 屬性來擷取內聯樣式,該樣式以原始單位儲存值。
Mozilla 和其他現代瀏覽器依賴 document.defaultView.getCompulatedStyle 方法來提供運算屬性。這些值被標準化為像素,從而在瀏覽器之間提供一致的表示。
跨瀏覽器解決方案
以下函數提供了一個跨瀏覽器解決方案,用於檢索內聯和內聯計算樣式:
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // Convert styleProp to compatible notation styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); // Modern browsers: computed properties if (defaultView && defaultView.getComputedStyle) { return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { // IE: inline properties // Convert styleProp to camelCase notation styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; // Normalize units on IE if (/^\d+(em|pt|%|ex)?$/i.test(value)) { return (function(value) { var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value || 0; value = el.style.pixelLeft + "px"; el.style.left = oldLeft; el.runtimeStyle.left = oldRsLeft; return value; })(value); } return value; } }
範例
要檢索id為「box」的元素的內聯寬度屬性(透過樣式標籤設定):
alert (getStyle(document.getElementById("box"), "width"));
要擷取計算的寬度屬性,該屬性需要考慮任何級聯或繼承樣式:
alert (getStyle(document.getElementById("box"), "width"));
限制
此函數無法完美處理顏色值。現代瀏覽器將以 rgb 表示法傳回顏色,而 IE 將保留其原始定義。
以上是如何使用純 JavaScript 從 HTML 元素中檢索樣式值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!