2010-04-14 60 views
2

第二個函數不起作用?不能讓jquery懸停使用.live()

$('.edit_hover').live('hover', 
    function(e){   
     $(this).stop(); 
     var half_width = ($(this).css('width').slice(0, -2))/2; 
     var half_height = ($(this).css('height').slice(0, -2))*0.3; 
     console.log(half_width); 
     var top = ($(this).position().top) + half_height; 
     var left = ($(this).position().left) + half_width; 
     $('#edit_hover').css('top', top).css('left', left).fadeIn(300); 
     //add overlay 
     $(this).css('position', 'relative').append('<div class="edit_overlay" style="position: absolute; top:0px; left:0px; height:100%; width: 100%; background: #999; opacity: 0.5;"></div> ') 
    }, 
    function(){ 
     $(this).stop(); 
     $(this).find('.edit_overlay').remove(); 
     $('#edit_hover').fadeOut(300); 
    }); 

回答

11

live()只需要一個處理程序,所以你不能使用hover(1.4.1之前)。無論如何,它只是mouseentermouseleave的快捷方式。使用這些事件綁定到:

$('.edit_hover') 
.live('mouseenter',function(){}) 
.live('mouseleave',function(){}); 

或者因爲jQuery的1.4.1:

$('.edit_hover').live('hover', function(event) { 
    if (event.type == 'mouseenter') { 
    // first function here 
    } else { 
    // second function here 
    } 
}); 
+0

+1謝謝!注意:我必須將'mouseover'更改爲'mouseenter',才能使腳本的第二部分工作。 – ILoveBrisbane 2011-03-24 11:53:03

+0

@ILoveBrisbane:對。 'hover'綁定'mouseenter'和'mouseleave',而不是'mouseover'。感謝您指出這一點....修正:) – 2011-03-24 13:36:23

+0

仍然似乎在1.6.2的情況 – mplungjan 2011-09-01 13:50:45

0

只是猜測:不使用hover使用mouseovermouseout

$("...").live("mouseover", function() { 
    // .... 
}).live("mouseout", function() { 
    // ... 
}); 
+0

'mouseover'和'mouseout'不工作方式相同'mouseenter'和'mouseleave'(事件,「懸停」是基於)。 – 2010-04-14 15:13:10

0

jQuery的是什麼版本的?您需要使用jQuery 1.4.1以現場方式使用hover。它在早期版本中不受支持。請參閱live documentation的注意事項部分。但是,請注意,您只有一個回調,需要區分回調內部的事件以獨立處理懸停/出局。

$('.hoverme').live('hover', function(event) { 
    if (event.type == 'mouseover') { 
    // do something on mouseover 
    } else { 
    // do something on mouseout 
    } 
});