簡體   English   中英

通過JS和Jquery獲取CSS元素值

[英]Get CSS element value by JS and Jquery

我以3種方式插入css

  • 內聯樣式(p1)
  • 內部樣式表(p2)
  • 外部樣式表(p3)

我希望通過Javascript && Jquery獲得每個css的價值。 請告訴我如何。

我不能以與p1相同的方式獲得p2,p3的值。 怎么了 ?

非常感謝 !

 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> 

**

強文

**

使用點表示法時,您需要一個屬性。 只有第一個元素具有style屬性,所以這就是為什么只有你的第一次嘗試才有效。

您可以使用window.getComputedStyle();獲取樣式屬性的值window.getComputedStyle(); getPropertyValue(); 請參閱下面的示例代碼,了解元素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