Home Web Front-end JS Tutorial JS gets CSS style (style/getComputedStyle/currentStyle)_javascript skills

JS gets CSS style (style/getComputedStyle/currentStyle)_javascript skills

May 16, 2016 pm 03:19 PM
css js

CSS styles are divided into three categories:
Inline style: is written in the Tag, and the inline style is only valid for all Tags.
Internal style: is written in HTML, and the internal style is only valid for the web page where it is located.
External style sheet: If many web pages need to use the same style (Styles), write the style (Styles) in a CSS file with the .css suffix, and then add it to each page. Reference this CSS file in a web page that needs to use these styles (Styles).

getComputedStyle is a method that can get all the final used CSS property values ​​​​of the current element. What is returned is a CSS style object ([object CSSStyleDeclaration])
currentStyle is a property of IE browser and returns a CSS style object

element refers to the DOM object obtained by JS
element.style //Only can get embedded styles
element.currentStyle //IE browser obtains non-embedded styles
window.getComputedStyle(element, pseudo-class) //Non-IE browsers get non-embedded styles
document.defaultView.getComputedStyle(element, pseudo-class)//Non-IE browsers get non-embedded styles
Note: Before Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), the second parameter "pseudo-class" was required (if not a pseudo-class, set to null), this parameter can now be omitted.

The following HTML contains two css styles. The div with id tag is an inline style, and the div with id test is an internal style.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus&reg;">
    <meta name="Author" content="Yvette Lau">
    <meta name="Keywords" content="关键字">
    <meta name="Description" content="描述">
    <title>Document</title>
    <style>
      #test{
        width:500px;
        height:300px;
        background-color:#CCC;
        float:left;
      }
    </style>
  </head>
  <body>
    <div id = "test"></div>
    <div id = "tag" style = "width:500px; height:300px;background-color:pink;"></div>
  </body>
</html>
Copy after login

JS part

<script type = "text/javascript">
  window.onload = function(){
    var test = document.getElementById("test");
    var tag = document.getElementById("tag");

    //CSS样式对象:CSS2Properties{},CSSStyleDeclaration
    console.log(test.style); //火狐返回空对象CSS2Properties{},谷歌返回空对象CSSStyleDeclaration{} 
    console.log(tag.style); //返回CSS2Properties{width:"500px",height:"300px",background-color:"pink"}
    //element.style获取的是内嵌式的style,如果不是内嵌式,则是一个空对象

    console.log(tag.style.backgroundColor);//pink
    console.log(tag.style['background-color']);//pink
    //获取类似background-color,border-radius,padding-left类似样式的两种写法啊

    console.log(test.currentStyle) //火狐和谷歌为Undefined,IE返回CSS对象
    console.log(window.getComputedStyle(test,null))//谷歌返回CSSStyleDeclaration{……} ,火狐返回CSS2Properties{……}
    console.log(window.getComputedStyle(test))
    //效果同上,但是在Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null)

    console.log(test.currentStyle.width);//500px(IE)
    console.log(window.getComputedStyle(test).width); //500px;
    console.log(window.getComputedStyle(test)['width']);//500px;
    //document.defaultView.getComputedStyle(element,null)[attr]/window.getComputedStyle(element,null)[attr]   
  }
</script>

Copy after login

The above examples are only to verify whether the previous discussion is correct.

For simplicity, we can also make a simple encapsulation of the acquisition style.

function getStyle(element, attr){
      if(element.currentStyle){
        return element.currentStyle[attr];
      }else{
        return window.getComputedStyle(element,null)[attr];
      }
    }
    console.log(getStyle(test,"cssFloat"));//left
    console.log(getStyle(test,"float"));  //left,早前FF和chrome需要使用cssFloat,不过现在已经不必
    console.log(getStyle(test,"stylefloat"));//火狐和谷歌都是undefined
    console.log(getStyle(test,"styleFloat")); //IE9以下必须使用styleFloat,IE9及以上,支持styleFloat和cssFloat

    console.log(window.getComputedStyle(test).getPropertyValue("float"))

Copy after login

Corresponding to the float style, IE uses styleFloat, while earlier FF and chrome used cssFloat. Now FF and Chrome already support float, and there are some other attributes. I will not list them one by one. In order not to To remember these differences, we introduce two methods of accessing CSS style objects:
getPropertyValue method and getAttribute method

IE9 and other browsers (getPropertyValue)
window.getComputedStyle(element, null).getPropertyValue(“float”);
element.currentStyle.getPropertyValue(“float”);
getPropertyValue does not support camel case notation. (Compatible with IE9 and above, FF, Chrom, Safari, Opera)
For example: window.getComputedStyle(element,null).getPropertyValue(“background-color”);

For IE6~8, you need to use the getAttribute method to access the attributes of the CSS style object

element.currentStyle.getAttribute("float");//No longer needs to be written as styleFloat
element.currentStyle.getAttribute("backgroundColor"); //The attribute name needs to be written in camel case, otherwise IE6 does not support it. If you ignore IE6, you can write it as "background-color"

The above is the entire content of this article. I hope it will be helpful to everyone's learning and easily use JS to obtain CSS styles.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles