简体   繁体   中英

jQuery - link working *only* after some time

I have a link:

<a href="#" id="link">Here's my link</a>

This is not a normal clickable link, it's coded in jQuery like this:

 $("#link").hover(function(e) { 
    e.preventDefault();   
    $("#tv").stop().animate({marginLeft: "50px"});
    $("#tv img)").animate({opacity: 1});
})  

So after hovering unclickable link there's change of #tv's margin and opacity.

Is there any way of making this work only after the user hovers the link area with pointer for more than two seconds?

Because now everything happens in real time.

I know there's delay() , but it doesn't work because it just delays the animation and in this case I don't want any action if the pointer is over for less than two seconds.

Possible without a loop?

你所追求的是hoverIntent

var animateTimeout;

$("#link").hover(function() {
  if (animateTimeout != null) { 
    clearTimeout(animateTimeout); 
  }
  animateTimeout = setTimeout(animate, 2000);
}, function() {
  clearTimeout(animateTimeout);
});

function animate() {
  //do animation
}

You just need a setTimeout() to delay the code, along with a clearTimeout() to clear it if the user leaves the link within 2 seconds.

Example: http://jsfiddle.net/mNWEq/2/

$("#link").hover(function(e) {
    e.preventDefault();
    $.data(this).timeout = setTimeout(function() {
        $("#tv").stop().animate({marginLeft: "50px"});
        $("#tv img)").animate({opacity: 1});
    }, 2000);
}, function(e) {
    clearTimeout($.data(this,'timeout'));
});

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