Как сказать .hover () ожидать?

Не запуская новую священную войну, чувства 'налогового сообщения' угловой скобки являются одной областью, где я чрезвычайно не соглашаюсь с Jeff. Нет ничего неправильно с XML, это довольно человекочитаемо (целый YAML или JSON, или файлы INI), но помните, что его намерение состоит в том, чтобы быть считано машинами. Большинство комбинаций языка/платформы идет с каким-то синтаксическим анализатором XML бесплатно, который делает XML довольно хорошим выбором.

кроме того, при использовании хорошего IDE как Visual Studio, и если XML идет со схемой, можно дать схему VS, и волшебно Вы получаете intellisense (можно добраться один для NHibernate, например).

Ulimately необходимо думать о том, как часто Вы собираетесь быть касанием этих файлов однажды в производстве, вероятно, не настолько часто.

Это все еще говорит все это для меня о XML и почему это - все еще допустимый выбор для файлов конфигурации (от Tim Bray ):

, "Если Вы хотите обеспечить данные общего назначения, что получатель мог бы хотеть сделать непредвиденные странные и сумасшедшие вещи с, или если Вы хотите быть действительно параноиками и требовательными в отношении i18n, или если, какая отправка you’re больше похожа на документ, чем структура, или если порядок вопросов данных, или если данные потенциально долговечны (как в, больше, чем секунды) XML, является способом пойти. Мне также кажется, что комбинация XML и XPath поражает зону наилучшего восприятия для форматов данных, которые должны быть расширяемы; то есть it’s, довольно легкий записать код обработки XML, который won’t приводят к сбою в присутствии изменений в формате сообщения, что don’t касаются части, о которой Вы заботитесь".

49
задан user3708642 9 June 2014 в 06:05
поделиться

4 ответа

personally I like the "hoverIntent" plugin:

http://cherne.net/brian/resources/jquery.hoverIntent.html

from the page: hoverIntent is a plug-in that attempts to determine the user's intent... like a crystal ball, only with mouse movement! It works like (and was derived from) jQuery's built-in hover. However, instead of immediately calling the onMouseOver function, it waits until the user's mouse slows down enough before making the call.

Why? To delay or prevent the accidental firing of animations or ajax calls. Simple timeouts work for small areas, but if your target area is large it may execute regardless of intent.

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config ) 

Configuration Options

sensitivity: If the mouse travels fewer than this number of pixels between polling intervals, then the "over" function will be called. With the minimum sensitivity threshold of 1, the mouse must not move between polling intervals. With higher sensitivity thresholds you are more likely to receive a false positive. Default sensitivity: 7

interval: The number of milliseconds hoverIntent waits between reading/comparing mouse coordinates. When the user's mouse first enters the element its coordinates are recorded. The soonest the "over" function can be called is after a single polling interval. Setting the polling interval higher will increase the delay before the first possible "over" call, but also increases the time to the next point of comparison. Default interval: 100

over: Необходимые. Функция, которую вы хотите вызвать onMouseOver. Ваша функция получает те же объекты "this" и "event", как и от метода зависания jQuery.

timeout: Простая задержка в миллисекундах перед вызовом функции out. Если пользователь снова наведет курсор на элемент до истечения тайм-аута, функция «out» не будет вызвана (и функция «over» не будет вызвана). Это в первую очередь для защиты от неаккуратных траекторий движения мышью человека, которые временно (и непреднамеренно) отвлекают пользователя от целевого элемента ... давая ему время вернуться. Тайм-аут по умолчанию: 0

выход: Необходимые. Функция, которую вы хотите вызвать onMouseOut. Ваша функция получает те же объекты «this» и «event», как и от метода зависания jQuery. Обратите внимание, hoverIntent будет вызывать функцию «out» только в том случае, если функция «over» была вызвана в том же запуске.

42
ответ дан 7 November 2019 в 11:29
поделиться

The general idea is to use setTimeout, like so:

$('.icon').hover(function() {
           $('li.icon > ul').slideDown('fast');
    }, function() { 
           setTimeout(function() {
                $('li.icon > ul').slideUp('fast');
           }, 2000);
    });

But this may do counterintuitive things if the user mouses out and then mouses in again quickly—this doesn't account for clearing the timeout when the user hovers over it again. That would require additional state.

1
ответ дан 7 November 2019 в 11:29
поделиться

This will make the second function wait 2 seconds (2000 milliseconds) before executing:

$('.icon').hover(function() {
    clearTimeout($(this).data('timeout'));
    $('li.icon > ul').slideDown('fast');
}, function() {
    var t = setTimeout(function() {
        $('li.icon > ul').slideUp('fast');
    }, 2000);
    $(this).data('timeout', t);
});

It also clears the timeout when the user hovers back in to avoid crazy behavior.

This is not a very elegant way of doing this, however. You should probably check out the hoverIntent plugin, which is designed to solve this particular problem.

75
ответ дан 7 November 2019 в 11:29
поделиться
$('.icon').on("mouseenter mouseleave","li.icon > ul",function(e){
   var $this = $(this);
   if (e.type === 'mouseenter') {
       clearTimeout( $this.data('timeout') );
       $this.slideDown('fast');
   }else{ // is mouseleave:
       $this.data( 'timeout', setTimeout(function(){
           $this.slideUp('fast');
       },2000) );  
   }
 });
1
ответ дан 7 November 2019 в 11:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: