Is there a way to hold the execution of the default action of a click even trigger on an <a>
element and resume it later?
I specifically do not mean cancelling the event and rewriting it later, as in:
document.getElementsByTagName("a")[0].addEventListener("click", function(event){
var url = this.getAttribute("href");
var target = this.getAttribute("target");
event.preventDefault();
setTimeout(function(){
console.log("TODO: open " + url + " in " + target);
}, 1000);
});
<a href="http://example.com" target="_blank">Click me!</a>
… neither triggering a brand new click:
var delayed = false;
document.getElementsByTagName("a")[0].addEventListener("click", function(event){
var link = this;
if (!delayed) {
event.preventDefault();
setTimeout(function(){
link.click();
}, 1000);
delayed = true;
}
});
<a href="http://example.com" target="_blank">Click me!</a>
function cloneEvent(event) {
return Object.setPrototypeOf(new Event(event.type), event);
}
var delayed = false;
document.getElementsByTagName("a")[0].addEventListener("click", function(event){
var newEvent = cloneEvent(event);
if (!delayed) {
event.preventDefault();
setTimeout(function(){
event.target.dispatchEvent(newEvent);
}, 1000);
delayed = true;
}
});
<a href="http://example.com" target="_blank">Click me!</a>
Why not?
Rewriting means you need to reinvent everything the browser would you (error prone and time consuming).
Triggering means it's no longer a user-initiated event (e.g. popup blocker) and the event cloning version doesn't even work.
I'm curious (main reason).
I get the impression that Event.preventDefault()上的延迟点击事件会使事件处于最终状态。我对么?这是不可能的吗?
答案 0 :(得分:0)
在有资格成为真正用户点击的链接集href='about:blank'
上,然后添加data-href=
网址。 eventListener 将data-href
值传递给包含在匿名函数中的函数,该函数设置超时。函数activateLink()
使用location.href
打开链接。
var lnx = document.links;
lnx[0].addEventListener('click', delayClick, false);
lnx.jsi.addEventListener('click', delayClick, false);
lnx.so.addEventListener('click', delayClick, false);
function delayClick(e) {
let destination = this.dataset.href;
setTimeout(function(e) {
activateLink(destination)
}, 1000);
}
function activateLink(destination) {
location.href = destination;
}
&#13;
a {
display:block;
margin: 10px 0;
}
&#13;
<a href='about:blank' data-href='https://example.com' target='_blank'>EXAMPLE</a>
<a id='jsi' href='about:blank' data-href='https://javascript.info' target='_blank'>JAVASCRIPT.INFO</a>
<a name='so' href='about:blank' data-href='https://stackoverflow.com' target='_blank'>STACKOVERFLOW</a>
&#13;