JavaScript Easy way to get css inter line style inner line style and outer chain style
- 2021-07-04 17:44:41
- OfStack
"Interline Style Acquisition"
<div id='div1' style="backgroud:red"> Test </div>
<script>
var odiv=document.getElementById('div1'); // First, get the element label to get the style, that is, get the div1
console.log(odiv.style.background); // So we can get the style between lines
</script>
"Inline Style Acquisition"
<html>
<head>
<style>
.div2{
background:red;
}
</style>
</head>
<body>
<div id="div1" class="div2"> Test </div>
<script>
var odiv=document.getElementById('div1'); // First, get the element label to get the style, that is, get the div1
//console.log(getComputedStyle(odiv,null).background); getComputedStyle(" Element " , " Pseudo class ") Is to get the calculated style, the 2 Parameters are pseudo-classes, if they are not directly used null But all evil IE8 And it is not supported before, so the following methods are needed
//console.log(currentStyle.background) This only has IE Self-support It is also the calculated style obtained
console(window.getComputedStyle?getComputedStyle(odiv,null).background:odiv.currentStyle); // Cross-browser compatibility
</script>
</body>
</html>
[External Chain Style Acquisition]
<html>
<head>
<link rel="stylesheet" type="text/css" href="basic.css" /> // Stylesheet of outer chain
</head>
<body>
<div id="div1" class="div2" > Test </div>
<script>
var sheet=document.styleSheets[0] // Get the style sheet to the outer chain
var rule=sheet.cssRules[0] // Gets the first in the outer chain style sheet 1 Styles
console.log(rule.style.background) //red So you can get the style specified in the outer chain style sheet
</script>
</body>
</html>
"Outside Chain Style Sheet"
.div2{
background:red;
}