gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:30:00 31 4
gpt4 key购买 nike

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

最佳答案

我建议使用元素作为某种模式,然后设置 css 属性 visibility往返隐藏可见

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

请参阅下面的示例:

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*/})

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

关于javascript - 确认后显示gif,直到在javascript中加载完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531215/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com