使用Javascript显示更改div宽度

问题描述 投票:0回答:2

我创建了这个进度条,显示了从A到B的距离,因此宽度在500s内从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>
javascript
2个回答
0
投票

你可以用setInterval()做这样的事情:

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

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

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

  textDiv.innerHTML = progressText;

}

0
投票

希望这对你有用,

我在这里使用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>
© www.soinside.com 2019 - 2024. All rights reserved.