简体   繁体   English

通过JS和Jquery获取CSS元素值

[英]Get CSS element value by JS and Jquery

I insert css in 3 ways 我以3种方式插入css

  • Inline style (p1) 内联样式(p1)
  • Internal style sheet (p2) 内部样式表(p2)
  • External style sheet (p3) 外部样式表(p3)

I want to get value of css in each by Javascript && Jquery . 我希望通过Javascript && Jquery获得每个css的价值。 Please show me how . 请告诉我如何。

I cant get the value of p2 , p3 in same way as p1 . 我不能以与p1相同的方式获得p2,p3的值。 What's wrong ? 怎么了 ?

Many thanks ! 非常感谢 !

 window.onload = abc(); function abc(){ var p1 = document.getElementById('p1').style.height; document.getElementById('p1').innerHTML = p1; var p2 = document.getElementById('p2').style.width; document.getElementById('p2').innerHTML = p2; var p3 = document.getElementById('p3').style.height; document.getElementById('p3').innerHTML = p3; } 
 #p3{ width: 200px; height: 200px ; background-color: aqua ; } 
 <!DOCTYPE html> <head> <title>CSS Element output</title> </head> <body> <H1>CSS output element property</H1> <div id="p1" style="height:50px;width:100px;">check p1</div> <div id="p2">check p2</div> <style> #p2{ height:50px; width:400px; background-color: bisque } </style> <div id="p3">check p3</div> </body> 

** **

strong text 强文

** **

When you use dot notation, you are asking for an attribute. 使用点表示法时,您需要一个属性。 Only the first element has a style attribute, so this is why only your first attempt works. 只有第一个元素具有style属性,所以这就是为什么只有你的第一次尝试才有效。

You can get value of style attributes using window.getComputedStyle(); 您可以使用window.getComputedStyle();获取样式属性的值window.getComputedStyle(); and getPropertyValue(); getPropertyValue(); Please see the sample code below for getting value of height for your element p2: 请参阅下面的示例代码,了解元素p2的高度值:

var element = document.getElementById('p2'),
    style = window.getComputedStyle(element),
    res = style.getPropertyValue('height');

alert(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM