Home >
Article > Web Front-end > JavaScript reads and sets style attributes of document elements_javascript tips
JavaScript reads and sets style attributes of document elements_javascript tips
WBOYOriginal
2016-05-16 18:54:221206browse
First, let’s talk about the style sheet attributes 1. The inline style is set in the style attribute of the element, with the highest level 2. The page style sheet definition is defined in the page, The next highest level is 3. External link style sheet file JavaScript gets and sets the css attribute of the document element: 1. Gets the style attribute set in the element's Style attribute, document.getElementById(id) .style.height; If yes, return the attribute value; if not, return empty Both IE and Firefox, but some attribute values may be returned differently, for example, for color, Firefox returns rgb, while IE returns ten Hexadecimal number Test code:
asdfasdfas
2. Sometimes our styles may be set in multiple places, and we don't know whether it works in external style sheet attributes or in inline styles, so we need Get the property value of the current page rendering. This is somewhat different in IE and FF: Sample code snippet: IE: document.getElementById('aaa').currentStyle.height FF standard: document.defaultView.getComputedStyle(aaa,null). getPropertyValue('height') These two properties are read-only. If you want to change the style of the element, you have to use style. It is written directly in the style attribute of the element and the highest level has effect. 3. Write an attribute that is compatible with IE and FF function to call
function getRealStyle(id, styleName) { var element = document.getElementById(id); var realStyle = null; if (element.currentStyle) realStyle = element.currentStyle[styleName]; else if (window .getComputedStyle) realStyle = window.getComputedStyle(element,null)[styleName]; return realStyle; }
Call: cur_height = parseInt(getRealStyle(CON_ID,' height')); P.S: The return value usually has a unit, you need to use the parseInt function to extract the number to facilitate subsequent operations
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn