确认后显示gif,直到在javascript中加载完成

时间:2017-04-20 22:56:27

标签: javascript html

我有一个包含“提交”按钮的表单。单击提交按钮后,将显示确认弹出窗口。一旦满足确认条件,就会发生HTTP帖子。但是,有时这篇文章可能需要一段时间。因此,我想在满足确认条件后显示加载gif,直到后响应返回,从而页面已经重新加载。

1 个答案:

答案 0 :(得分:1)

我建议使用一个元素作为某种模态,然后将{css属性visibility设置为hiddenvisible

然后,您可以在按下按钮时添加事件处理程序,并请求隐藏或显示此元素。

请参阅以下示例:

const requestButton = document.querySelector('.request');
const yes = document.querySelector('.yes');
const no = document.querySelector('.no');
const confirmation = document.querySelector('.confirmation');
const loading = document.querySelector('.loading');
const content = document.querySelector('.content');

requestButton.addEventListener('click', event => {
  confirmation.style.visibility = 'visible';
});

yes.addEventListener('click', event => {
  // instead of a setTimeout, you'd actually make a request using `fetch` or jquery ajax
  loading.style.visibility = 'visible';
  confirmation.style.visibility = 'hidden';
  window.setTimeout(() => {
    // the code in this callback would be the same code you'd put in your `success` callback
    // i.e. this code should run when the request finishes
    loading.style.visibility = 'hidden';
    const p = document.createElement('p');
    p.innerText = 'Loaded!';
    content.appendChild(p);
  }, 2000);
});

no.addEventListener('click', event => {
  confirmation.style.visibility = 'hidden';
});
.hidden-center {
  position: absolute;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0;
  left: 0;
  visibility: hidden;
}

.modal {
  background-color: lightgray;
  padding: 3em;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="content">
  <button class="request">load a thingy?</button>
</div>
<div class="confirmation hidden-center">
  <div class="modal">
    Are you sure?
    <div>
      <button class="yes">Yes</button>
      <button class="no">No</button></div>
  </div>
</div>
<div class="loading hidden-center">
  <div class="modal">
    <div>Loading...</div>
    <i class="fa fa-spinner fa-spin fa-3x"></i>
  </div>
</div>

修改

阅读上面的评论,看起来你的应用程序不是单页面应用程序(我现在只是假设)。您不需要将事件侦听器附加到按钮单击,而是需要将事件侦听器附加到表单,如下所示:

document.querySelector('#my-form-id').addEventListener('submit', event => {/*code to show loading*/})

此外,您可能不需要为返回的请求添加事件侦听器,因为新文档将替换当前的文档。