首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.mouseleave()和.mouseenter()

.mouseleave()和.mouseenter()
EN

Stack Overflow用户
提问于 2015-08-21 20:15:08
回答 3查看 92关注 0票数 1

我使用.mouseenter()和.mouseleave()来制作动画来解决button.The的问题,当我多次在按钮上移动光标时,它会不断重复动画的.For .mouseenter(),我希望它在游标一直盘旋到动画时间结束之前完成动画,如果在动画完成之前它离开了按钮,那么动画就应该停止,如果光标在动画完成之前悬停在它上面。

代码语言:javascript
复制
  $(document).ready(function(){
    $('#button').mouseenter(function(){
        $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100);
    });
    $('#button').mouseleave(function(){
        $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100);
    });   
  });
代码语言:javascript
复制
#button{
  width:100px;
  height:50px;
  background-color:red;
  }
代码语言:javascript
复制
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
<div id="button"></div>

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-21 20:53:20

您可以使用标志进入和离开。然后检查适当的标志,并在enter/ like事件发生时完成当前的动画,如下所示:

代码语言:javascript
复制
$(document).ready(function () {
    var isEntering = false, // Create flags
        isLeaving = false;
    $('#button').mouseenter(function () {
        isEntering = true; // Set enter flag
        if (isLeaving) {   // Check, if leaving is on process
            $(this).finish(); // If leaving, finish it
            isLeaving = false; // Reset leaving flag
        }
        $(this).animate({
            backgroundColor: '#ffce00',
            width: '+=1em'
        }, 100);
    });
    $('#button').mouseleave(function () {
        isLeaving = true; // Set leave flag
        if (isEntering) { // Check if entering is on process
            $(this).finish(); // If it is, finish it
            isEntering = false; // Reset enter flag
        }
        $(this).animate({
            backgroundColor: '#1e7989',
            width: '-=1em'
        }, 100);
    });
});

jsFiddle现场演示

票数 2
EN

Stack Overflow用户

发布于 2015-08-21 20:29:26

尝试添加.stop(),它将停止动画排队。

代码语言:javascript
复制
$(document).ready(function(){
    $('#button').mouseenter(function(){
        $(this).stop().animate({backgroundColor:'#ffce00',width:'+=1em'},100);
    });
    $('#button').mouseleave(function(){
        $(this).stop().animate({backgroundColor:'#1e7989',width:'-=1em'},100);
    });
});

你好,加道斯

票数 1
EN

Stack Overflow用户

发布于 2015-08-21 20:24:43

如果只希望它运行一次,则可以在事件触发后解除绑定:

代码语言:javascript
复制
$(document).ready(function(){
    $('#button').mouseenter(function(){
        $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100);
        $(this).unbind('mouseenter');
    });
    $('#button').mouseleave(function(){
        $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100);
        $(this).unbind('mouseleave');
    });   
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32148613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档