簡體   English   中英

內部div的事件累積來自外部div的事件數

[英]Event for an inner div accumulates the number of event from the outer div

我有一個看起來像這樣的html標記:

<div class="student">

    <div class="student-main-image">  
        <div id="student-image-154"><img src="http://goo.gl/5wMt0o"></div>
    </div>

    <div class="student-info">
        Johnna Smith
    </div>

</div>

我想做的就是簡單地將包含一些文本的內部div滑入和滑出。 如果將父容器懸停,則在內部div中滑動,否則將其滑出,但如果在懸停主div之后立即將其懸停,則保持內部div不顯示。

如果父div懸停了,我就能完成內div的滑入和滑出操作,但是我無法弄清楚為什么當它在父div之后懸停時,內div會不斷地上下滑動。

有什么我想念的嗎?

這是我當前的js代碼:

$(".student .student-main-image").hover(function () {

    $(this).next().slideDown("fast");
    console.log('in');

}, function(){

    $(this).next().hover(function () {
        $(this).slideDown("fast");
        console.log('in');
    }, function(){
        $(this).slideUp("fast");
        console.log('out');
    }); 

    if($(this).next().is(":visible")) {
        $(this).next().slideUp("fast");
        console.log('hide it');
    } else {
        console.log('nothing to hide');
    }

}); 

小提琴: http : //jsfiddle.net/9857R/1/

您需要查看html樹。 當您將鼠標懸停在文本元素上時,鼠標將離開圖像元素。

這將導致文本向下滑動,將鼠標移回圖像元素上方,從而導致其向上滑動,從而陷入永久循環。

使用包含兩個容器的主容器將事件綁定到。 由於text元素包含在main元素內,因此將鼠標懸停在子元素上不會引起問題,因為鼠標永遠不會離開父元素

然后,您可以將代碼縮減為:

$(".student ").hover(function () {          
    $(this).find('.student-info').stop(true,true).slideToggle("fast");    
}); 

stop()用於防止事件排隊,如果您最終在動畫完成之前再次移動鼠標

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM