jquery делегирование событий

0

Я пытаюсь переписать фрагмент кода с помощью делегирования событий (в надежде, что он прекратит конфликт с другим snippiet js). но я сломал код

оригинал

//to scale up on hover
var current_h = null;
var current_w = null;

$('.piccon').hover(
    function(){
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({width: (current_w * 2.7), height: (current_h * 2.7)}, 900);
    },
    function(){
        $(this).stop(true, false).animate({width: current_w + 'px', height: current_h + 'px'}, 400);
    }
);

//использование делегирования событий

//to scale up on hover
var current_h = null;
var current_w = null;

$('#videoandmapwrap').on("hover","img", function(event){
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({width: (current_w * 2.7), height: (current_h * 2.7)}, 900);
    },
    function(){
        $(this).stop(true, false).animate({width: current_w + 'px', height: current_h + 'px'}, 400);
    }
  event.preventDefault();
);

Выяснить из-за Placeholder

//to reveal from behind placeholder picture
           $('#videoandmapwrap').on("click","img",function(event){
             event.preventDefault();
        video = '<iframe class="piccon" width="200" height="200" src="'+ $(this).attr('data-video') +'"></iframe>';
        $(this).replaceWith(video);  
    });
  • 1
    Измените его на on("hover",".piccon", ... если вы хотите точное поведение.
Теги:
event-delegation

1 ответ

2

Объект .hover() не является событием, это просто метод утилиты, который добавляет обработчики mouseenter и mouseleave, поэтому, когда вы хотите использовать делегирование делегирования, вам нужно зарегистрировать обработчики для этих 2 событий вместо использования hover

$(document).on({
    mouseenter: function () {
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({
            width: (current_w * 2.7),
            height: (current_h * 2.7)
        }, 900);
    },
    mouseleave: function () {
        $(this).stop(true, false).animate({
            width: current_w + 'px',
            height: current_h + 'px'
        }, 400);
    }
}, '.piccon');

Или

$('#videoandmapwrap').on({
    mouseenter: function () {
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).stop(true, false).animate({
            width: (current_w * 2.7),
            height: (current_h * 2.7)
        }, 900);
    },
    mouseleave: function () {
        $(this).stop(true, false).animate({
            width: current_w + 'px',
            height: current_h + 'px'
        }, 400);
    }
}, 'img');

Другой способ написать то же самое

$('#videoandmapwrap').on('mouseenter', function () {
    current_h = $(this, 'img')[0].height;
    current_w = $(this, 'img')[0].width;
    $(this).stop(true, false).animate({
        width: (current_w * 2.7),
        height: (current_h * 2.7)
    }, 900);
}, 'img').on('mouseleave', function () {
    $(this).stop(true, false).animate({
        width: current_w + 'px',
        height: current_h + 'px'
    }, 400);
}, 'img');
  • 0
    спасибо Арун, это было очень поучительно. К сожалению, шкала при наведении перестает отвечать, как только я нажимаю на картинку (чтобы показать видео, скрытое за заполнителем рисунка), я думал, что делегирование события решит проблему. ты знаешь как я мог переписать код? Я изменил свой вопрос, чтобы включить другой код

Ещё вопросы

Сообщество Overcoder
Наверх
Меню