<a> element

时间:2018-04-04 13:27:20

标签: javascript dom-events

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?

  1. Rewriting means you need to reinvent everything the browser would you (error prone and time consuming).

  2. Triggering means it's no longer a user-initiated event (e.g. popup blocker) and the event cloning version doesn't even work.

  3. I'm curious (main reason).

I get the impression that Event.preventDefault()上的延迟点击事件会使事件处于最终状态。我对么?这是不可能的吗?

1 个答案:

答案 0 :(得分:0)

在有资格成为真正用户点击的链接集href='about:blank'上,然后添加data-href= 网址 eventListener data-href值传递给包含在匿名函数中的函数,该函数设置超时。函数activateLink()使用location.href打开链接。

演示

&#13;
&#13;
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;
&#13;
&#13;