简体   繁体   English

内部div的事件累积来自外部div的事件数

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

I have an html markup that looks like this: 我有一个看起来像这样的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>

What I am trying to do is to simply slide in and out the inner div that contains some text. 我想做的就是简单地将包含一些文本的内部div滑入和滑出。 Slide in the inner div if the parent container is hovered and slide it out otherwise but maintain the inner div from being displayed if it is hovered right after the main div was hovered. 如果将父容器悬停,则在内部div中滑动,否则将其滑出,但如果在悬停主div之后立即将其悬停,则保持内部div不显示。

I am able to accomplish sliding in and out the inner div if the parent div is hovered but I can't figure out why the inner div continuously slides up and down when it is hovered right after the parent div. 如果父div悬停了,我就能完成内div的滑入和滑出操作,但是我无法弄清楚为什么当它在父div之后悬停时,内div会不断地上下滑动。

Is there something that I'm missing? 有什么我想念的吗?

Here is my current js code: 这是我当前的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');
    }

}); 

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

You need to look at the html tree. 您需要查看html树。 When you open the text element with your mouse over it your mouse is leaving the image element. 当您将鼠标悬停在文本元素上时,鼠标将离开图像元素。

This causes the text to slide down putting your mouse back over the image element causing it to then slide up and you get stuck in a perpetual loop. 这将导致文本向下滑动,将鼠标移回图像元素上方,从而导致其向上滑动,从而陷入永久循环。

Use the main container that holds both to bind the events to. 使用包含两个容器的主容器将事件绑定到。 Since the text element is contained within the main element, hovering the child doesn't cause issues because mouse never left the parent 由于text元素包含在main元素内,因此将鼠标悬停在子元素上不会引起问题,因为鼠标永远不会离开父元素

Then you can reduce your code down to: 然后,您可以将代码缩减为:

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

stop() is used to prevent queuing of events should you end up moving mouse again before animation is completed stop()用于防止事件排队,如果您最终在动画完成之前再次移动鼠标

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM