点击加载栏不起作用



尝试使用 onClick 制作加载栏,但它不会触发。

function click_01() {
    var elem = document.getElementById('trash_02');
    setInterval(frame, 10);
    var width = 1;
    function frame(){
       if (width >= 100){
            clearInterval(frame);
            width = 0;
       } else {
            width = width + 1;
            elem.style.width = width + '%';
       }
      }
    }  

您无法清除函数框架,您需要为间隔指定一个变量名称,然后将其清除。

var elem = document.getElementById('trash_02');
var width = 0;
var progressInterval;
elem.addEventListener('click', progressBar);
function progressBar() {
  // Name the interval to a variable
  progressInterval = setInterval(frame, 10);
};
function frame() {
  if (width < 100) {
    width++;
    elem.style.width = width + '%';
  } else {
    // We need to clear the interval variable
    clearInterval(progressInterval);
    width = 0;
  }
}
#trash_02 {
  background: red;
  height: 50px;
  width: 50px;
  cursor: pointer;
}
<div id='trash_02'></div>

如果需要,您可以在本地设置变量,这是我目前想到的两种方法;

  • 代替 frame(( 函数,您可以在设置的间隔内定义匿名函数,并在 progressBar(( 函数中定义变量。

  • 或者你可以在 progressBar(( 函数中定义变量,并在 progressBar(( 函数中编写 frame(( 函数。

最新更新