2017-01-06 43 views
1

我目前正在尝试创建一个小动画时,徘徊 div使用.animate() jQuery函数。mouseleave动画之前奇怪的意外延迟

如果您看一下代码片段,您会发现在鼠标离开div和动画启动之间存在非常奇怪的延迟。

这肯定是一些与.animate()功能,因为,有一个console.log当鼠标离开div和没有任何奇怪的延迟时显示。

我错过了什么或...任何想法将不胜感激!

谢谢!

$(document).ready(function() { 
 
    $(".square").hover(function() { 
 
     var _this = this; 
 
     $(_this).find(".square-hover").eq(0).animate({ 
 
     top: "0px", 
 
     }, 750) 
 
    }) 
 
    $(".square").mouseleave(function() { 
 
     var _this = this; 
 
     console.log("mouseleave triggered"); 
 
     $(_this).find(".square-hover").eq(0).animate({ 
 
     top: "-300px", 
 
     }, 100) 
 
    }); 
 
})
.square { 
 
    box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 1px 5px 0 rgba(0,0,0,0.12), 0 3px 1px -2px rgba(0,0,0,0.2); 
 
    padding: 0; 
 
    border: 1px solid rgba(255, 255, 255, 0.1); 
 
    height: 200px; 
 
    -webkit-transition-property: background-color; 
 
    -webkit-transition-duration: 0.2s; 
 
    overflow: hidden; 
 
    margin-top: 5px 
 
} 
 

 
.square-hover{ 
 
    position: absolute; 
 
    top: -300px; 
 
    width: 100%; 
 
    height: 100%; 
 
    background-color: rgba(29, 233, 182, 0.85); 
 
}
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<div class="col-xs-6 col-xs-offset-3 square"> 
 
    <div class="square-hover"></div> 
 
</div>

+1

代码应该**在这里发布**。 – Pointy

回答

2

的问题是因为你使用hovermouseleavehover事件处理程序实际上是分开的mouseentermouseleave处理程序 - 所以您实际上附加了1 mouseenter和2 mouseleave。这是你问题的原因。

如果你改变了代码传递两个函数来hover(先为mouseenter,第二个用于mouseleave)你的代码工作:

$(".square").hover(function() { 
    $(this).find(".square-hover").eq(0).stop(true).animate({ 
     top: "0px", 
    }, 750) 
}, function() { 
    $(this).find(".square-hover").eq(0).stop(true).animate({ 
     top: "-300px", 
    }, 100) 
}); 

Updated fiddle

还要注意在上面使用stop(true)以防止连续事件堵塞动画队列。

+0

好得多!感谢'strop(true)'提示。 – Xor

+0

似乎,如果我们离开并进入快速,悬停div保持盘旋。 – Xor

+0

多数民众赞成在奇怪的 - 这是什么'停止(真)'应该防止 –