繁体   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