Master Stylesheet Effects on display Style
When displaying content using HTML's display style, it's essential to understand how inline and master stylesheets affect its behavior. This article explores the issue where myDiv.style.display returns an empty string when set in a master stylesheet, unlike when set inline.
Initial State of display
HTML elements typically start with a default display value, usually "inline". To override this, developers often use inline styles:
<div>
However, to increase maintainability, it's beneficial to set these initial styles in a master stylesheet.
Unexpected Behavior
When setting display:none in a master stylesheet, the initial state of the element remains hidden. However, accessing myDiv.style.display using JavaScript initially returns an empty string. This differs from inline styles, where it returns "none".
Resolved Issue Using getComputedStyle
The solution to this issue lies in understanding that accessing an element's CSS properties directly (e.g., element.style.display) retrieves their inline style settings. To access styles defined in external stylesheets or browser defaults, developers must use the getComputedStyle method:
function getStyle(id, name) { var element = document.getElementById(id); return element.currentStyle ? element.currentStyle[name] : window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null; } var display = getStyle('myDiv', 'display'); alert(display); // prints 'none' or 'block' or 'inline' etc.
By utilizing getComputedStyle, developers can accurately retrieve values set externally, including those in master stylesheets.
The above is the detailed content of Why Does `myDiv.style.display` Return an Empty String When Set in a Master Stylesheet?. For more information, please follow other related articles on the PHP Chinese website!