Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

javascript - How to have a mouseover event fire only if the mouse is hovered over an element for at least 1 second?

I want to display a dialog when a user mouses over a certain image. That part works. Unfortunately if the mouse even just passes over the corner of the image quickly it will display the dialog. I would like to have the dialog show only if the mouse is left over the image for one full second so as to avoid inadvertent pop ups.

I saw this question but it is for jQuery and I am using Prototype. I don't know enough jQuery to interpret that solution.

If someone could explain the logic or JavaScript functionality that will be required to cause a delayed firing of the mouseover event I would appreciate it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't delay the firing of the event, but you can delay your handling of the event.

Here's a quick example without jQuery or Prototype that will make it easier to understand.

var delay = function (elem, callback) {
    var timeout = null;
    elem.onmouseover = function() {
        // Set timeout to be a timer which will invoke callback after 1s
        timeout = setTimeout(callback, 1000);
    };

    elem.onmouseout = function() {
        // Clear any timers set to timeout
        clearTimeout(timeout);
    }
};


delay(document.getElementById('someelem'), function() {
    alert("Fired");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...