2014-01-10 102 views
0

我試圖用事件代理重寫一段代碼(希望它會停止與另一個js的snippiet衝突)。但我已經斷碼jquery事件代表團

原始

//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(); 
); 

顯示從後面佔位

//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

更改它開啓(「懸停」,「。piccon」,...,如果你想要確切的行爲。 –

回答

2

.hover()不是一個事件是隻是增加了一個mouseenter和實用方法3210個處理器,所以當你想使用事件委派你需要使用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'); 

另一種方式來寫的登記處理那些2個事件,而不是同樣是

$('#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

謝謝阿倫,這是很有啓發。不幸的是懸停規模一旦我點擊圖片停止響應(揭示隱藏在圖片佔位符後面的視頻)我想事件的代表團將解決這個問題。你知道我可以如何重寫代碼嗎?我已經修改了我的問題以包含其他代碼 – Vynce82