在没有库的情况下从 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中文网其他相关文章!