首页 > 解决方案 > 执行加载按钮几秒钟

问题描述

我自己设计了一个加载按钮。如果用户点击一个按钮,加载按钮将显示几秒钟,然后在再次点击该按钮之前不再显示。

此代码显示了工作原理的示例。

HTML:

<div id="loader" style="display:none"></div>
<button class="button" onclick="load()">Loading Button</button>

CSS:

#loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border: 16px solid #f3f3f3;
    border-radius: 50%;
    border-top: 16px solid #3498db;
    width: 120px;
    height: 120px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

JS

function load() {
  document.getElementById("loader").style.display = "block";
  setTimeout(stop(), 5000)
}

function stop() {
  document.getElementById("loader").style.display = "none";
}

我的问题是加载按钮没有被调用,但从未显示。我猜这是因为页面上的元素在运行完 js 函数后会刷新,所以只处理最后一个关于“loader”-ID 的命令。

有谁知道也考虑第一个命令的方法?

谢谢你的帮助,

博辛加

标签: buttonloading

解决方案


function load() {
  document.getElementById("loader").style.display = "block";
  setTimeout(stop(), 5000)
} 

问题是 setTimeout 将立即调用停止功能,并且您的加载程序将永远不会显示。

function load() {
  document.getElementById("loader").style.display = "block";
  setTimeout(function(){
    document.getElementById("loader").style.display = "none"; }, 3000);
}

在这种情况下,您只能调用一个函数,这将起作用

https://stackblitz.com/edit/js-yyokfc?file=index.html 工作示例

如果您使用 XMLHttpRequest 将 style.display = "block" 设置为微调器的默认状态,并在请求函数中调用停止函数

let request = new XMLHttpRequest();
    request.open('GET', "" true);
 // This will be called after the response is received
    request.onload = function () {
      // stop spinner
         stop();
     // do stuff

    }
    request.send();

推荐阅读