Javascript 当有人单击特定链接时如何显示加载对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13626237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display loading dialog when someone clicks a specific link?
提问by sorin
I do have an URL which opens a webpage which is very slow to load and I have no control over it.
我确实有一个 URL,它打开一个加载非常缓慢的网页,我无法控制它。
I do want to display a loading dialog when someone clicks this URL or to block page with an overlay div when this happens.
我确实想在有人单击此 URL 时显示加载对话框,或者在发生这种情况时使用覆盖 div 阻止页面。
Note: this is not the same question as the ajax related ones, this for normal URL clicks form the user, not all of them only specific ones.
注意:这与 ajax 相关的问题不同,这适用于来自用户的正常 URL 点击,并非所有这些都只是特定的。
<A href="http://veryslowload.com" onClick="...">slow load...</a>
I suppose that what I am looking for is what to put on the onClick.
我想我正在寻找的是放在 onClick 上的内容。
回答by Denys Séguret
You can do this :
你可以这样做 :
$(function(){
? $('a').click(function(){
$('<div class=loadingDiv>loading...</div>').prependTo(document.body);
});?
});
Demonstration(change the link to a very slow page for best effect)
演示(将链接更改为非常慢的页面以获得最佳效果)
But it depends on the page : if the page sends immediately some content but not the whole content, you won't have the time to see your div.
但这取决于页面:如果页面立即发送一些内容而不是全部内容,您将没有时间查看您的 div。
回答by FrancescoMM
If you also need an animation, it becomes a complicated matter as browsers behave very differently. Some stop all GIF animations when a new page starts loading. Basically it comes down to something like this if you have jQuery and download the spin.js library.
如果您还需要动画,这将变得很复杂,因为浏览器的行为非常不同。当新页面开始加载时,有些会停止所有 GIF 动画。如果您有 jQuery 并下载 spin.js 库,基本上它会归结为这样的事情。
See working solution here:
请参阅此处的工作解决方案:
<style>
#loading {
display:none;
position:absolute;
left:0;
top:0;
z-index:1000;
width:100%;
height:100%;
min-height:100%;
background:#000;
opacity:0.8;
text-align:center;
color:#fff;
}
#loading_anim {
position:absolute;
left:50%;
top:50%;
z-index:1010;
}
</style>
<div id="loading"><div id="loading_anim"></div></div>
<a href="http://pangoo.it" class="mylinkclass withanimation">link</a>
<script>
$(function () {
$(".withanimation").click(function(e) {
e.preventDefault();
$("#loading").show();
var url=$(this).attr("href");
setTimeout(function() {
setTimeout(function() {showSpinner();},30);
window.location=url;
},0);
});
});
function showSpinner() {
var opts = {
lines: 15, // The number of lines to draw
length: 3, // The length of each line
width: 4, // The line thickness
radius: 30, // The radius of the inner circle
rotate: 0, // The rotation offset
color: '#fff', // #rgb or #rrggbb
speed: 2, // Rounds per second
trail: 70, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
$('#loading_anim').each(function() {
spinner = new Spinner(opts).spin(this);
});
}
</script>
If you use an animated (GIF) the animation may freeze on some browsers. I used spin.js library ( http://fgnass.github.com/spin.js/). While GIFs get frozen the javascript animation seems to be working.
如果您使用动画 (GIF),动画可能会在某些浏览器上冻结。我使用了 spin.js 库(http://fgnass.github.com/spin.js/)。当 GIF 被冻结时,javascript 动画似乎正在运行。
Please test with ALL browsers!
请使用所有浏览器进行测试!
回答by bfavaretto
Although ajax would be more elegant, it's possible. You have to intercept the navigation by preventing the default event, then force an update to the UI, then change the location to the destination url. Something like this:
虽然ajax会更优雅,但这是可能的。您必须通过阻止默认事件来拦截导航,然后强制更新 UI,然后将位置更改为目标 url。像这样的东西:
$('#mylink').click(function(e) {
e.preventDefault();
var url = this.href;
// Update the UI here
setTimeout(function() {
// This is a trick to force a repaint
window.location.href = url;
},0);
});
回答by AmericanUmlaut
Presumably, you'll want the loading dialog to appear immediately, then to disappear and be replaced by the new page when the new page has rendered?
据推测,您希望加载对话框立即出现,然后在新页面呈现后消失并由新页面替换?
Three ideas come to mind.
三个想法浮现在脑海中。
If you have control of the source page but not the target - Use a click event handler to replace the tags' normal behavior with something like this:
如果您可以控制源页面但不能控制目标 - 使用单击事件处理程序将标记的正常行为替换为如下所示:
- Display the loading animation
- Fire an AJAX request to the URL defined by the tag's href attribute (alternately, create a hidden with the URL as its source)
- When the request has completed, replace the document's contents with the response.
- 显示加载动画
- 向标签的 href 属性定义的 URL 发出 AJAX 请求(或者,创建一个以 URL 作为源的隐藏)
- 请求完成后,用响应替换文档的内容。
This can get really hairy, though, since you won't lose javascript and css defined in the original page. It also won't change the URL displayed in the user's browser.
但是,这可能会变得非常麻烦,因为您不会丢失原始页面中定义的 javascript 和 css。它也不会更改用户浏览器中显示的 URL。
If you have control of the target and can make the target cacheable (even for a few seconds): You could load the page in the background via AJAX and then redirect to it. The first load will be slow, then the redirect will load the page from cache.
如果您可以控制目标并且可以使目标可缓存(即使是几秒钟):您可以通过 AJAX 在后台加载页面,然后重定向到它。第一次加载会很慢,然后重定向将从缓存中加载页面。
And yet another alternative: If you have control of the target page, you can define an optional parameter such that if the parameter is present, the server returns a page consisting of only the loading animation and a bit of javascript that loads the actual page.
还有另一种选择:如果您可以控制目标页面,您可以定义一个可选参数,如果该参数存在,服务器将返回一个页面,该页面仅包含加载动画和一些加载实际页面的 javascript。
回答by Hussain Akhtar Wahid 'Ghouri'
initially store a spinner.gif some where in your form and keep it hidden and also put src=""
最初将 spinner.gif 存储在表单中的某个位置并将其隐藏并放置 src=""
thus there will be no src for image
因此将没有图像的 src
but later on while making the ajax call you can set the src for the spinner image thus you page will seem to be loading
但稍后在进行 ajax 调用时,您可以为微调图像设置 src,因此您的页面似乎正在加载
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'url to be called',
type:'post',
beforeSend:function()
{
alert("this is the place where you place things to happen till your page is being transfered to the given URL so i am setting the src for the spinner image here");
$("#spinner image ID").attr("src","../images/spinner.gif");
},
success:function(e){
alert("do whatever you want with response here");
}
});
});
回答by David Hellsing
You can create a hidden iframe and listen for the load event. You will also need to do a manual check after about 1 sec, in case the destination has prevented x-frame content.
您可以创建一个隐藏的 iframe 并侦听加载事件。您还需要在大约 1 秒后进行手动检查,以防目的地阻止了 x 帧内容。
DEMO: http://jsbin.com/ijofih/1
$('a').click(function(e) {
$(this).text('Loading...'); // do your UI thing here
e.preventDefault();
var destination = this.href;
setTimeout(function() {
window.location = destination;
},1000);
$('<iframe>').hide().appendTo('body').load(function() {
window.location = destination;
}).attr('src', destination);
});
回答by Frank
This is an old topic, but if you want a simple solution that doesn't depend on JQuery add the following to onClick in your link:
这是一个老话题,但如果您想要一个不依赖于 JQuery 的简单解决方案,请将以下内容添加到您链接中的 onClick 中:
<A href="http://veryslowload.com" onClick=""javascript:document.getElementById('page-loader').style.display='block';"">slow load...</a>
Then somewhere on your page, have a hidden DIV that includes what you want for the loading dialog.
然后在你的页面上的某个地方,有一个隐藏的 DIV,其中包含你想要的加载对话框。
<div id="page-loader">
<h3>Loading page...</h3>
</div>
and hide the DIV with CSS as follows:
并使用 CSS 隐藏 DIV,如下所示:
#page-loader {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 25px;
background-color: rgba(255, 255, 255, 0.7);
}
Here's a JSfiddle to a working example: http://jsfiddle.net/meb69vqd/
这是一个工作示例的 JSfiddle:http: //jsfiddle.net/meb69vqd/
I can't take full credit for this example. There are additional tips about this technique here: https://css-tricks.com/css-page-loader/
我不能完全相信这个例子。这里有关于此技术的其他提示:https: //css-tricks.com/css-page-loader/
回答by Harry Moreno
an improvement over @bfavaretto 's solution that worked for me
对@bfavaretto 对我有用的解决方案的改进
$('#mylink').click(function(e) {
e.preventDefault();
var url = this.href;
// Update the UI here
requestAnimationFrame(function() {
setTimeout(function() {
window.location.href = url;
});
});
});
the browser would inconsistently display my spinner. I tried hacking around with increasing the setTimeout's delay. The proper solution is to ask the browser when it is ready to show the spinner, then navigate away.
浏览器会不一致地显示我的微调器。我尝试通过增加 setTimeout 的延迟来解决问题。正确的解决方案是询问浏览器何时准备好显示微调器,然后导航离开。
回答by Hawiak
You might want to look into Modal boxes. You can activate a model box when the ajax request is send and on success maybe close it. https://www.google.com/search?sugexp=chrome,mod=10&sourceid=chrome&ie=UTF-8&q=modal+box
您可能想查看模态框。您可以在发送 ajax 请求时激活模型框,并在成功时关闭它。 https://www.google.com/search?sugexp=chrome,mod=10&sourceid=chrome&ie=UTF-8&q=modal+box

