簡體   English   中英

使用Java顯示變化的div寬度

[英]Display changing div width with Javascript

我創建了這個進度條,顯示了從A到B的距離,因此寬度在500 s內從10%變為100%,我使用@keyframes做到了。 是否可以在進度條內將變化的div寬度顯示為標簽?

這是我當前的代碼

 // I tried creating a function like this but it did not work out function addProcent() { var totaal = document.getElementById("huidigeAfstand").offsetWidth; var text = document.getElementById("text"); text.innerHTML(totaal); }; 
 #afstandTotaal { width: 100%; height: 30px; margin-top: 15px; margin-left: 0; margin-right: 0; background-color: #d7d7d7; } #huidigeAfstand { width: 10%; height: 30px; background: #F48024; animation: afstandloper 500s; animation-iteration-count: 1; } @keyframes afstandloper { from { width: 10%; } to { width: 100%; } } 
 <div id="afstandLabel"><cite>Afstand tot Mars vanaf deze locatie.</cite></div> <div id="afstandTotaal"> <div id="huidigeAfstand"> <span id="text">Aantal</span> </div> </div> 

您可以使用setInterval()做類似的事情:

const progress = document.querySelector('#huidigeAfstand');

setInterval(() => setProgress() , 1000)

function setProgress() {
  const progressText = progress.getBoundingClientRect().width;
  const textDiv = document.querySelector('#text');

  textDiv.innerHTML = progressText;

}

希望這對您有用,

我在這里使用setInterval函數,並每隔5秒更新#huidigeAfstand的寬度,直到#huidigeAfstand的寬度等於#afstandTotaal。

 function addProcent(){ var parentWidth= document.getElementById("afstandTotaal").offsetWidth; var childWidth = document.getElementById("huidigeAfstand").offsetWidth; var i=0.01*parentWidth; var changeValue= function () { if(i<parentWidth) { childWidth+= i; document.getElementById("huidigeAfstand").innerHTML=childWidth.toFixed(2); } else { clearInterval(intervalID); } } var intervalID= setInterval(changeValue, 5000); }; 
 #afstandTotaal { width: 100%; height: 30px; margin-top: 15px; margin-left: 0; margin-right: 0; background-color: #d7d7d7; } #huidigeAfstand { width: 10%; height: 30px; background: #F48024; animation: afstandloper 500s; animation-iteration-count: 1; } @keyframes afstandloper { from {width: 10%;} to {width: 100%;} } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body onload="addProcent()"> <div id="afstandLabel"><cite>Afstand tot Mars vanaf deze locatie.</cite></div> <div id="afstandTotaal"> <div id="huidigeAfstand"> <span id="text">Aantal</span> </div> </div> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM