当前位置:网站首页>DOM style operation
DOM style operation
2022-07-22 16:03:00 【Front grass seed】
Catalog
1. obtain script Script node Element nodes loaded later , You can't get it ,
2.css Data in style structure Cannot get through the node object
1. obtain script Script node Element nodes loaded later , You can't get it ,
<body>
<script>
var box2 = document.querySelector('.box2');
console.log(box2); //null
</script>
<div class="box2" style="color:red;">666</div>
</body>
analysis : obtain script After the script node div Elements , I can't get it , console.log(box2); //null
Because documents are loaded in the order of the document tree , First, it runs script Get in script .box2, Then define below .box2
If you must get script Script node Element nodes loaded later , There are two ways :
01. When the page is loaded, the event is triggered , Then go to the method of obtaining nodes
Get access to .box2 Put your code into the function , Wait until the page is loaded before running this function
<body>
<script>
function fn() {
// Write it in the function Let's get box2 Code for , Ratio definition box2 Code after running
var box2 = document.querySelector('.box2');
console.log(box2); //null
}
//window.load When the whole document is loaded, it will be called automatically fn
window.onload = fn;
</script>
<div class="box2" style="color:red;">666</div>
</body>
02.script -- defer async modification src How to load external js Asynchronous properties of resources
Asynchronous loading of scripts
1):
<script src="script.js"></script>
No, defer or async, The browser loads and executes the specified script immediately ,“ immediately ” It means rendering the script Before the document element under the tag , That is, not waiting for subsequent document elements to load , Load and execute as soon as you read it .
2):
<script async src="script.js"></script>
Yes async, The process of loading and rendering subsequent document elements will follow script.js Load and execute in parallel ( asynchronous ).
3):
<script defer src="myscript.js"></script>
Yes defer, The process of loading subsequent document elements will be the same as script.js The loading is done in parallel ( asynchronous ), however script.js After all elements are parsed ,DOMContentLoaded Before the event triggers .
And then from a practical point of view , First put all the scripts script It's all here </body> It was best practice before , Because it's the only optimization option for old browsers , This method can ensure that all other non script elements can be loaded and parsed with the fastest speed .
<body>
<script defer src="./test.js"></script>
<div class="box2" style="color:red;">666</div>
</body>
result : Can print out box2 <div class="box2" style="color:red;">666</div>
2.css Data in style structure Cannot get through the node object
<body>
<style>
.box2{
width: 200px;
height: 200px;
background-color: blue;
font-size: 50px;
}
</style>
<div class="box2" style="color:red;" >666</div>
<button id="btn"> Click on </button>
<script>
// demand : Push the button at one click ,box2 The font size of is *2
var btn = document.querySelector('#btn');
btn.addEventListener('click',function(){
var box2 = document.querySelector('.box2');
console.log(box2.style.fontSize,11111); // An empty string ,11111
});
</script>
</body>
analysis : There's no problem with the code , It's just font-size The writing position is different , Just box2.style.fontSize The result is different .
Combine diagram and code analysis : var box2 = document.querySelector('.box2'); Through this code , We are operating the document tree , Get the element node inside , Is in DOM Inside the tree . however font-size:50px; Write it in the style sheet , Then go to the style structure ,DOM Trees and style structures are two different data containers , Cannot from DOM Inside the tree , Get the style in the style structure through the element node . What then? font-size:50px; Written in div You can access it in the tag ? because font-size:50px; Written in div The tag belongs to the attribute node , It belongs to the document tree . So you can get attribute nodes from element nodes .
Now the question is , Not all css The code is written in the line , quite a lot css The code is all written in style Inside the label , Or outside css file , Then introduce the . How to get through JS(dom Trees ) The element object inside to get the style in the style structure ? Use the official offer window.getComputedStyle();
3. Official functions :window.getComputedStyle(); // Gets the calculation style ( Present... In the tree )
Be careful : I use a new one here that I haven't used before Get the method of element attribute , And this window.getComputedStyle() Method , It can only be used to obtain attribute values , But it cannot be used to modify attribute values , So in the error prompt read-only
<body>
<style>
.box2{
width: 200px;
height: 200px;
background-color: blue;
font-size: 50px;
}
</style>
<div class="box2" style="color:red;" >666</div>
<button id="btn"> Click on </button>
<script>
// demand : Push the button at one click ,box2 The font size of is *2
var btn = document.querySelector('#btn');
btn.addEventListener('click',function(){
var box2 = document.querySelector('.box2');
var box2_style = window.getComputedStyle(box2);// obtain box2 Calculation style of ( Present... In the tree )
console.log(box2_style.fontSize); //50px
// Notice that this is box2.style.fontSize instead of box2_style.fontSize
// because hese styles are computed, and therefore the 'font-size' property is read-only.
box2_style.fontSize = parseInt(box2_style.fontSize)*2 + 'px';
});
</script>
</body>
边栏推荐
- Nftscan and port3 have reached strategic cooperation in the field of NFT data
- 企业需要建立属于自己的小程序及APP需要做什么前期工作?
- ctfshow MengXIn 下
- P6327 interval plus interval sin sum
- Collagen protease loaded albumin composite nanoparticles / bovine serum albumin coated ceria nano artificial enzyme
- C language outputs the number of all daffodils
- SSTI simple summary and ciscn 2019 southeast China]double secret
- Online RPC timeout troubleshooting and subsequent GC tuning ideas
- 浅拷贝,深拷贝(实现方式)
- DOM之12种节点
猜你喜欢
随机推荐
C language outputs the number of all daffodils
对接三方支付接口需要满足哪些需求?
P6327 区间加区间sin和
Leetcode high frequency question: zigzag (zigzag, zigzag) sequence traversal of binary tree
High school education self-study test, I took 10K in Shenzhen at the age of 21, and only I know how much I paid~
ENVI_IDL: 批量制作专题地图
常见的probe set和gallery set究竟是什么
DC-4-靶场实践
机器学习基础篇(5)图像轮廓
BookPageCnt
Matlab simulation of BER performance of BCH coding and decoding
线段树学习记录
GoldenSection
LastWordLen
Metauniverse enabling scenario Finance: a new track for the competitive development of commercial banks
Mo team problem sorting
C language to write 99 multiplication table to realize the output of tables with different triangle shapes
为什么我们开发的系统会有并发Bug,并发Bug根源到底是什么?
Web3 社交协议垄断性与灵魂绑定代币
[code Notes] - u-net