Accessing Style from Master Stylesheet with JavaScript
When setting the display property of a div to "none" in a master stylesheet and attempting to access it via JavaScript using myDiv.style.display, you may encounter a blank return value. This is because there is a distinction between inline styles and computed styles.
Inline styles are set directly on the HTML element itself, while computed styles are a combination of all the styles applied to an element, including those set in external stylesheets or parent elements. When an inline style is present, it overrides any conflicting computed style.
When you access the style property of an element via JavaScript, you are only able to read the inline styles. Therefore, if you set the display property to "none" in the master stylesheet but have an inline style that overrides it, myDiv.style.display will return an empty string.
To access the computed style, you need to use the getComputedStyle() function. This function returns an object that contains all the computed styles for an element, including those set in external stylesheets or parent elements.
Here's an example of how to use getComputedStyle() to retrieve the computed display property:
var display = getComputedStyle(myDiv).display;
By using getComputedStyle(), you can access the computed style of an element, even if it has been overridden by an inline style.
The above is the detailed content of How to Access Computed Styles with JavaScript When Inline Styles Override Master Stylesheet Settings?. For more information, please follow other related articles on the PHP Chinese website!