我想当用户点击任何外部链接(由任何特定id或类标识)在我的网站上,那么他应该得到一个10秒的计数器弹出,10秒后,弹出窗口应该关闭,用户应该能够访问外部URL。如何做到这一点?我可以像下面这样显示一个警告,但我不知道如何添加超时,而且这是一个confirm
框,而不是一个弹出框,我可以添加一些div
和更多的东西给用户看,直到计数器停止。
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS:有没有免费的插件?
我准备了一个小演示来帮助你。首先要注意的是,您将需要使用JavaScript中的setTimeout函数。其次,确认框和警告窗口不会给你所需的灵活性。这是我的HTML,首先我显示了一个简单的链接,然后创建了一个弹出式div,它将从用户视图隐藏。
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
接下来,我创建了一个对象来控制如何显示弹出窗口,并在弹出窗口中处理相关事件。这主要是为了保持我的弹出代码在一个地方,所有的事件集中位于对象内。
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
如果你运行,你会看到弹出显示和倒计时是正确的倒数。当然还有一些需要调整的地方,但你应该能够看到完成的总体思路。希望能有所帮助!
JS提琴样例:http://jsfiddle.net/u39cV/
您不能使用confirm native对话框作为这种对话框,因为alert()
会阻止所有脚本的执行。你必须使用非阻塞的自定义对话框。
即使这个有模态选项,这不是UI阻塞
考虑使用javascript setTimeout
函数在给定延迟后执行操作
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}