js获取元素CSS值的各种方法分析

先来看一个实例:如何获取一个没有设置大小的字体?

1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style>#div4{font-size:40px}</style> 7 </head> 8 <body> 9 <p>10</p> 10 <div>未设置大小的文字</div> 11 <div>使用js设置大小20px的文字</div> 12 <div>使用行内css设置大小30px的文字</div> 13 <div>使用style标签设置大小40px的文字</div> 14 <script> 15 console.log(document.getElementById("div1").style.fontSize) //输出空白 16 console.log(document.getElementById("div2").style.fontSize="20px") //输出空白20px 17 console.log(document.getElementById("div3").style.fontSize) //输出空白30px 18 console.log(document.getElementById("div4").style.fontSize) //输出空白 19 20 var style = div1.currentStyle || document.defaultView.getComputedStyle(div1, \'\') 21 console.log(style.fontSize);//可以输出div1到div4的正确字体大小 22 </script> 23 </body> 24 </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzxyjf.html