简体   繁体   中英

jquery/javascript blur/focus & settimeout

When mouse is over a product number (focus) then show some product information. When user is not longer over a product number (blur), then wait 3 seconds, then hide details.

$('.productNumber').live('blur', function() {               
    setTimeout(function(){
    var divToPutData = $(this); 
    divToPutData.hide();
}, 3000);
});

Now user says that if user moves mouse back within those 5 seconds to stop the count down, until a blur event fires again. No sure how to do this with setTimeout.

Use clearTimeout()

var myTimeout = null;

$('.productNumber').live('mouseover', function() {  
    //If timeout is still active, clear
    if(myTimeout != null)
        clearTimeout(myTimeout);
});

$('.productNumber').live('blur', function() {
    //Store the ID returned by setTimeout
    myTimout = setTimeout(function(){ divToPutData.hide(); }, 3000);
});

Use the function clearTimeout.

setTimeout returns a numeric id, you can store it in a variable, and then pass it to the clearTimeout function:

var myTimeout = setTimeout ( function(){alert(2);}, 1000);
clearTimeout(myTimeout);
var t;
$('.productNumber').live('mouseover', function() {  
    clearTimeout(t);
});

$('.productNumber').live('mouseout', function() {               
    t = setTimeout(function(){
    divToPutData.hide();
}, 3000);
});

have the setTimeout assigned to a variable, so you can cancel it on hover again

var hideTimeout;
$('.productNumber').live('blur',function() {
    hideTimeout = setTimeout(function() {
        divToPutData.hide();
    }, 3000);
});
$('.productNumber').live('mouseover',function() {
    clearTimeout(hideTimeout);
    // Do the show stuff
}
  • jQuery is not my strongest language, so you may need to modify this slightly, but this is the general approach to this scenario.

Use the jQuery stop() to abort any ongoing animation

Test it here: http://jsfiddle.net/T7kRr/1/

jQuery

$(".productNumber").hover(
  function () {
      $(this).find(".productDesc:last").stop(true, true).show();
  }, 
  function () {
      $(this).find(".productDesc:last").delay(3000).fadeOut(); 
  }
);

HTML

<div class="productNumber">1001<span class="productDesc" style="display:none">iPhone</span></div>
<div class="productNumber">2001<span class="productDesc" style="display:none">iPad</span></div>
<div class="productNumber">3333<span class="productDesc" style="display:none">TV</span></div>
<div class="productNumber">9999<span class="productDesc" style="display:none">HiFi</span></div>

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