在沒有庫的情況下從JavaScript 檢索HTML 元素的樣式值
透過JavaScript 存取HTML 元素的樣式時,您可能會面臨檢索方面的挑戰由
要取得計算的樣式值,包括
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // W3C standard way: if (defaultView && defaultView.getComputedStyle) { // sanitize property name to css notation // (hypen separated words eg. font-Size) styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { // IE // sanitize property name to camelCase styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; // convert other units to pixels 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; } }
用法:
// Getting width style value var width = getStyle(document.getElementById("box"), "width"); // Getting color style value (may differ between browsers) var color = getStyle(document.getElementById("box"), "color");
以上是如何在不使用庫的情況下從 JavaScript 中的 HTML 元素檢索樣式值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!