简体   繁体   中英

How do I make a mouseover stick until a page refresh?

I want a mouseover event to be handled after a delay, and then be inactive until a page refresh.

This is my code thus far:

$(function() {
    $("#page-flip").mouseover(function() { 
        $(".box").toggleClass("box-change");
        $(".films").toggleClass("films-change");
        $(".synopsis").toggleClass("synopsis-change");
    });
});

How do I add a time delay to this and than have it inactive after being fully triggered once? Thank you :)

You can use .one() to have an event handler only trigger once:

$(function() {
    //bind a mouseover event handler that will fire only once
    $("#page-flip").one('mouseover', function() { 

        //set a timeout so the code runs after half a second
        setTimeout(function () {

            //run your code here
            $(".box").toggleClass("box-change");
            $(".films").toggleClass("films-change");
            $(".synopsis").toggleClass("synopsis-change");
        }, 500);
    });
});

Here is a demo: http://jsfiddle.net/jasper/fWakf/3/

Documentation: http://api.jquery.com/one

You could also use .off() :

$(function() {
    $("#page-flip").on('mouseover', function() { 

        //remove this event handler so it doesn't fire in the future
        $(this).off('mouseover');
        setTimeout(function () {
            $(".box").toggleClass("box-change");
            $(".films").toggleClass("films-change");
            $(".synopsis").toggleClass("synopsis-change");
        }, 500);
    });
});

Here is a demo: http://jsfiddle.net/jasper/fWakf/4/

Note that .on() is new in jQuery 1.7 and in this case is the same .bind() . .off() is also new so if you're using older than 1.7 and .bind() , then use .unbind() .

Edit This answer is worse than Jasper's . But the pattern it uses doesn't require jQuery, so I'm leaving it up.


Well, you could go simple and use a global variable, or complicated and remove the event entirely.

the simple one looks like this.

 var __GlobalEventFired = false;
 $(function() { 
 $("#page-flip").mouseover(function() {  
    if(!__GlobalEventFired)
    {
       __GlobalEventFired = true;
       $(".box").toggleClass("box-change"); 
       $(".films").toggleClass("films-change"); 
       $(".synopsis").toggleClass("synopsis-change"); 
    }
}); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM