2010-12-29 2 views
0

У меня есть сценарий, как этотJQuery: Mouseover Timeout

$('.parent a').live('mouseover mouseout', function(event) { 
    if (event.type == 'mouseover'){ 
     if ($(this).siblings('.child').css('width') == '0px' ){ 
      $(this).siblings('.child').animate({'width': window.innerWidth}, 500); 
     } 
    }else{ 
     if (!$(this).hasClass('active')){ 
      $(this).siblings('.child').animate({'width': 0}, 500); 
     } 
    } 
}); 

, как вы заметили из сценария выше, если мышь над $('.parent a') то это родственный расширит его ширину.

для теперь своих братьев и сестер exapnd мгновенно, если мышь над, я хочу, чтобы это произошло, когда мы уже мыши над после 5 seconds

, как это сделать?

ответ

4

Обратите внимание, что я добавил отдельных прослушивателей событий, а не тестировал внутри обработчика событий для разных типов событий.

var timer; 

$('.parent a').live('mouseover', function(event) { 
    $Sibling = $(this).siblings(".child"); 
    timer = window.setTimeout(function() { 
     if ($Sibling.css('width') == '0px' ){ 
      $Sibling.animate({'width': window.innerWidth+"px"}, 500); 
     }}, 5000); 
}); 

$('.parent a').live('mouseout', function(event) { 
    if (timer) { 
     window.clearTimeout(timer); 
    } 
    if (!$(this).hasClass('active')){ 
     $(this).siblings('.child').animate({'width': "0px"}, 500); 
    } 
}); 

Идея заключается в том, что вы устанавливаете таймер для запуска, когда пользователь нажимает на якорь. Если они выталкиваются до запуска таймера, вы очищаете таймер, чтобы остановить событие. В противном случае, когда срабатывает таймер, он будет расширять элемент в соответствии с вашим оригинальным скриптом.

Кроме того, получая jQuery для прохождения DOM только один раз и сохранения результата в $ Sibling, мы делаем скрипт быстрее.

Чтобы проверить это, я использовал следующий HTML.

<div class="parent"> 
     <a href="#">Hello</a> 
     <div class="child" style="background-color: Aqua; display: block; width: 0px; overflow: hidden;">World</div> 
    </div> 
0

вы можете использовать SetTimeout

$('.parent a').live('mouseover mouseout', function(event) { 
    var elements = $(this).siblings('.child'); 
    if ($(this).siblings('.child').css('width') == '0px' ){ 
     setTimeout(animate(elements, window.innerWidth), 5000); 
    } 
}else{ 
    if (!$(this).hasClass('active')){ 
     setTimeout(animate(elements, 0), 5000); 
    } 

}); 

function animate(elements, width) { 
    elements.animate({'width': width}, 500); 
} 
0

Вы хотите сохранить таймер здесь через setTimeout() и очищается с помощью clearTimeout(), но вы всегда хотите сделать это на элемент, который вы можете сделать с помощью $.data() , как это:

$('.parent a').live({ 
    mouseover: function() { 
    var self = this; 
    $.data(this, "timer", setTimeout(function() { 
     if ($(self).siblings('.child').css('width') == '0px' ){ 
     $(self).siblings('.child').animate({'width': window.innerWidth}, 500); 
     } 
    }, 5000)); 
    }, 
    mouseout: function() { 
    clearTimeout($.data(this, "timer")); 
    if (!$(this).hasClass('active')){ 
     $(this).siblings('.child').animate({'width': 0}, 500); 
    } 
    } 
}); 

You can test it out here, я считаю выше легче читать в JQuery 1.4.3+, но если вы используете более раннюю версию, просто отформатировать его, как вы были раньше:

$('.parent a').live('mouseover mouseout', function(event) { 
    if (event.type == 'mouseover'){ 
    var self = this; 
    $.data(this, "timer", setTimeout(function() { 
     if ($(self).siblings('.child').css('width') == '0px' ){ 
     $(self).siblings('.child').animate({'width': window.innerWidth}, 500); 
     } 
    }, 5000)); 
    }else{ 
    clearTimeout($.data(this, "timer")); 
    if (!$(this).hasClass('active')){ 
     $(this).siblings('.child').animate({'width': 0}, 500); 
    } 
    } 
}); 

You can confirm that works here.