JavaScript gets DOM node HTML element CSS style

Source: Internet
Author: User

JavaScript gets DOM node HTML element CSS style Technology

Maybe yes posted on 2015-01-10 18:07

Original link: http://blog.lmlphp.com/archives/59 from: lmlphp backyard

How do I use JavaScript to get CSS style values for HTML elements under a DOM node? Children's shoes using jquery must be very familiar, jquery provides a very powerful CSS method that can easily set and get the style property of the element.

In some cases, when we cannot use JQuery, we must use pure JavaScript to get the value of the element's style property. This article describes the style values for getting elements using pure JavaScript.

There are four ways to control the page using CSS, in-line style (inline style), inline, link, import, respectively.

The inline style (inline style) is written in the Style property in the HTML tag to control the element style, as in the following code example:

<div style= "width:100px;height:100px;" ></div>

The inline style is written in the Style tab, as shown in the following code example:

<style type= "Text/css" >div{width:100px; height:100px}</style>

The link is the introduction of a CSS file with the link tag, as shown in the following code example:

<link href= "/static/css/main.css?v=1" type= "Text/css" rel= "stylesheet"/>

Import is the introduction of the CSS file with import, the following code example:

@import url ("/static/css/main.css?v=1")

You can use the Style property to get a CSS style, but a style can only get inline styles for elements. Therefore, to get the complete style information for an element, you must use the getComputedStyle method of the Window object, which has 2 parameters, the first parameter is the element to get the calculated style, the second argument can be null, an empty string, a pseudo-class (for example: before,: After), both of these parameters are required. The getComputedStyle method is not implemented in IE8 browsers, but you can use each element in IE to get a style with its own Currentstyle property. The compatible code that gets the element style is as follows:

<style type= "Text/css" > #eleid {font-size:14px;} </style><div id= "Eleid" ></div><script>var ele = document.getElementById ("Eleid"); var style = window.getComputedStyle?  window.getComputedStyle (Ele, ""): Ele.currentstyle;var font_size = style.fontsize; 14px;</script>

Gets the <link> and <style> label write styles that get a style sheet through stylesheets. This method can only get the declaration when the style, and the actual operation after the difference, the following example:

var obj = document.stylesheets[0];if (obj.cssrules) {//non ie [object cssrulelist]rule = Obj.cssrules[0]; } else {//IE [Object cssrulelist]rule = Obj.rules[0];}

Some of the methods of acquiring styles that are circulated online are collected as follows:

var css = function  (_obj,_name) {    var result;         //Convert to lowercase         _name = _ Name.tolowercase ();         //Get style values          if (_name && typeof value ===  ' undefined ') {             //if the attribute exists in style[]   (Operation get inline style sheet  inline  Style sheets)             if (_obj.style  && _obj.style[_name]) {                 result = _obj.style[_name];             }            // Manipulate an embedded style sheet or an external style sheet &NBSP;EMBEDDED&NBSP;STYLE&NBsp;sheets and linked style sheets             else if (_obj.currentstyle) {                  //  otherwise   try IE's currentstyle                  _name = _name.replace (/\-([ A-z]) ([A-z]?) /ig,function (s,a,b) {                     return a.touppercase () +b.tolowercase ();                 });                 result = _obj.currentStyle[_name];             }             //or the method   if present  Firefox,Opera,safari             else if (document.defaultview &&  Document.defaultView.getComputedStyle) {                 //gets the value of the Style property if it exists                  var w3cstyle = document.defaultview.getcomputedstyle (_obj,  null);                 Result = w3cstyle.getpropertyvalue (_name);             }            if (Result.indexOf (' px ')!=-1)  result = result.replace (/(PX)/I, ');             return result;        }    } 
<script type= "Text/javascript" >function getstyle ( elem, name ) {     //if the attribute exists in style[], it has recently been set (and is current)     if  (Elem.style[name])      {        return elem.style[name];     }    //Otherwise, try IE's way     else if  (Elem.currentstyle)      {        return elem.currentStyle[name];     }    //or a way to do it, if it exists     else if  ( Document.defaultview && document.defaultview.getcomputedstyle)     {         //it uses the traditional "text-align" style of writing rules, rather than "textAlign"          name = name.replace (/([A-z])/g, "-$1");         name =&nbSp;name.tolowercase ();         //gets the style object and takes the value of the property (if one exists)          var s = document.defaultview.getcomputedstyle (Elem, "");         return s && s.getpropertyvalue (name);     //Otherwise, you are using a different browser     }    else     {        return null;    }}</ Script>

However, for the float property in CSS, because JavaScript uses float as a reserved word, it cannot be used as a property name, so there is a substitute for "stylefloat" in IE, and in Firefox, Safari, Opera and chrome are "cssfloat". Therefore, compatibility-based considerations can change the style operation to the following form:

element: The target element that needs to get the style; Name: style attribute Function getstyle (element, name)  {    var  computedStyle;    try {         Computedstyle = document.defaultview.getcomputedstyle (element, null);     }  catch  (e)  {        computedStyle =  element.currentstyle;    }    if  (name !=  "float")  {        return computedStyle[name];     } else {        return computedstyle["CssFloat"]  | |  computedstyle["Stylefloat"];    }}//element: the target element in which the style is to be set; Name: Style property; value: Set Value function  setstyle (Element, name, value)  {    if  (name !=  "float ") &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;   element.style[name] = value;    } else {         element.style["Cssfloat"] = value;         element.style["Stylefloat"]&NBSP;=&NBSP;VALUE;&NBSP;&NBSP;&NBSP;&NBSP;}}

Read (69) reviews (0) View comments


JavaScript gets DOM node HTML element CSS style

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.