


JS gets CSS style (style/getComputedStyle/currentStyle)_javascript skills
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®"> <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>
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>
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"))
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.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)