[英]Change id width percentage with javascript
我正在嘗試編寫百分比目標欄。 我似乎無法在javascript中更改#bar寬度百分比。 有什么建議嗎?? 抱歉,代碼混亂。 我有-20 * -1的理由。 我只需要集中精力更改ID寬度百分比即可。
CSS:
.graph {
width: 500px; /* width and height are arbitrary, just make sure the #bar styles are changed accordingly */
height: 30px;
border: 1px solid #888;
background: rgb(168,168,168);
position: relative;
}
#bar {
height: 29px; /* Not 30px because the 1px top-border brings it up to 30px to match #graph */
width: 34%;
float: left;
background: rgb(255,197,120);
border-top: 1px solid #fceabb;
}
JS:
var _first = -20 * -1;
var _second = 150;
var _third = _first / _second * 100;
document.getElementById('bar').style.width = _third + "%";
HTML:
<center><div id="progress" class="graph"><div id="bar"></div></div></center>
由於JS在DOM准備就緒之前就已加載,因此無法找到尚未加載的帶有ID bar
的div
,因此應將代碼放入onload
函數中:
window.onload=function(){
var _first = -20 * -1;
var _second = 150;
var _third = _first / _second * 100;
document.getElementById('bar').style.width = _third + "%";
}
希望這可以幫助。
您的代碼是正確的。 只是出故障了。 當您的JavaScript嘗試操作DOM時,瀏覽器尚未創建它。 有兩種方法,這就是我的方法。 我喜歡這種方式,因為不需要等待等待DOM創建的額外函數。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
.graph {
width: 500px;
height: 30px;
border: 1px solid #888;
background: rgb(168,168,168);
position: relative;
}
#bar {
height: 29px;
width: 34%;
float: left;
background: rgb(255,197,120);
border-top: 1px solid #fceabb;
}
</style>
<!-- The HTML needs to come before the JavaScript. That way
the DOMS are created for the JavaScript -->
<center>
<div id="progress" class="graph">
<div id="bar"></div></div>
</center>
<script>
var _first = -20 * -1;
var _second = 150;
var _third = _first / _second * 100;
document.getElementById('bar').style.width = _third + "%";
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.