[英]How can I read a CSS property value using Javascript?
function displayWidth(){ document.getElementById("navbar").className = "navbar-after-click"; alert(document.getElementById("navbar").style.width); }
#navbar { background-color:red; height:200px; } .navbar{ width :220px; } .navbar-after-click{ width:60px; }
<html> <body> <div id="navbar" class="navbar"> </div> <button type="button" onclick="displayWidth();">show width </button> </body> </html>
我不太熟悉Javascript,所以才問這個問題。 在上面的代碼中,我嘗試使用Javascript警告CSS屬性值。 但這並沒有像我預期的那樣提醒任何價值。 我的代碼有什么問題嗎? 我怎樣才能解決這個問題?
使用getComputedStyle
Plknr演示:
http://plnkr.co/edit/BQEdwqeZgZ1Nc02ZeAzQ?p=preview
堆棧摘要:
function displayWidth(){ document.getElementById("navbar").className = "navbar-after-click"; var nav = document.getElementById("navbar"); var navWidth = window.getComputedStyle(nav,null).getPropertyValue("width"); alert(navWidth); }
#navbar { background-color:red; height:200px; } .navbar{ width :220px; } .navbar-after-click{ width:60px; }
<html> <body> <div id="navbar" class="navbar"> </div> <button type="button" onclick="displayWidth();">show width </button> </body> </html>
您可以通過jQuery找到它。
$("#navbar").css("width")
使用此腳本進行代碼
<script type="text/javascript">
function displayWidth(){
var element = document.getElementById('navbar');
var style = window.getComputedStyle(element);
alert(style.width); //style. all possible objects list in the end
}
</script>
演示:
<!DOCTYPE html> <html> <head> <style> #navbar { background-color:red; height:200px; } .navbar{ width :220px; } .navbar-after-click{ width:60px; } </style> <script src="/scripts/snippet-javascript-console.min.js?v=1"></script> </head> <body> <html> <body> <div id="navbar" class="navbar"> </div> <button type="button" onclick="displayWidth();">show width </button> </body> </html> <script type="text/javascript"> function displayWidth(){ var element = document.getElementById('navbar'); style = window.getComputedStyle(element); alert(style.width); } </script> </body> </html>
樣式。 //以下鏈接中所有可能的對象列表
這是解決方案。
function displayWidth(){
var style = window.getComputedStyle(document.getElementById("navbar"), null);
var width= style.getPropertyValue("width");
console.log(width);
}
使用offsetWidth獲取寬度
<!DOCTYPE html> <html> <style> #navbar { background-color:red; height:200px; } .navbar{ width :220px; } .navbar-after-click{ width:60px; } </style> <body> <div id="navbar" class="navbar"> </div> <button type="button" onclick="displayWidth();">show width </button> </body> <script type="text/javascript"> function displayWidth(){ document.getElementById("navbar").className = "navbar-after-click"; alert(document.getElementById("navbar").offsetWidth); } </script> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.