admin管理员组

文章数量:1289529

In JavaScript, I have an element (which is an input tag).

This code :

element.addEventListener("focus", function () {
    this.parentNode.parentNode.style.outline = this.parentNode.parentNode.dataset.ans_outline;
});

When the input is focused, outline is changed immediately.

My question is : how could I delay this event ?

I've tried :

element.addEventListener("focus", function () {
    setTimeout(function(node) {
        node.parentNode.parentNode.style.outline = node.parentNode.parentNode.dataset.ans_outline;
    }(this), 1000)
});

.. But it doesn't work :(

In JavaScript, I have an element (which is an input tag).

This code :

element.addEventListener("focus", function () {
    this.parentNode.parentNode.style.outline = this.parentNode.parentNode.dataset.ans_outline;
});

When the input is focused, outline is changed immediately.

My question is : how could I delay this event ?

I've tried :

element.addEventListener("focus", function () {
    setTimeout(function(node) {
        node.parentNode.parentNode.style.outline = node.parentNode.parentNode.dataset.ans_outline;
    }(this), 1000)
});

.. But it doesn't work :(

Share Improve this question asked Dec 10, 2015 at 13:12 JerryJerry 1,2381 gold badge14 silver badges21 bronze badges 1
  • you are calling the function inside of the timeout, hence why it is not working. – epascarello Commented Dec 10, 2015 at 13:18
Add a ment  | 

2 Answers 2

Reset to default 5

try this:

element.addEventListener("focus", function () {
    var node = this;
    setTimeout(function() {
        node.parentNode.parentNode.style.outline = node.parentNode.parentNode.dataset.ans_outline;
    }, 1000)
});

First argument of setTimeout function is function you want to execute (do not call this function directly).

You can store reference to this in node variable and then use it inside your timed out function (see closures)

Remove the reference to the this and give it this way:

element.addEventListener("focus", function () {
    $this = this;
    setTimeout(function() {
        $this.parentNode.parentNode.style.outline = $this.parentNode.parentNode.dataset.ans_outline;
    }, 1000)
});

本文标签: javascriptDelay eventListenerStack Overflow