jQuery 动画的意外行为

4

So I made this animated sidebar:

HTML

<div class="sidebar">
    <div class="block"><a class="link" href="#link1">Menu Option 1</</div>
    <div class="block">Menu Option 2</div>
    <div class="block">Menu Option 3</div>
    <div class="block">Menu Option 4</div>
</div>

CSS

.sidebar{
    position:fixed;
    height:100%;
    width:200px; 
    top:0;
    left:0;
    z-index: 100;
}

.block{
    width:5%;
    height: 20px;
    border-style: solid;
    border-width: 1px;
    text-indent: 100%;
    text-align: right;
    white-space: nowrap;
    overflow: hidden;
    background-color: red;
    padding: 10px;
}

.link{
    text-indent: 100%;
    text-align: right;
    white-space: nowrap;
    width:100%;
    height: 100%;
}

#slider {
    border:1.5px solid black;
    width:10px;
    position:fixed;
}

jQuery

//Sidbar Animations
$(".block").mouseover(function() {
  $(this)
    .animate({
      width: "90%"
    }, {
      queue: false,
      duration: 400
    }).css("text-indent", "0");
});
$(".block").mouseout(function() {
  $(this)
    .animate({
      width: "5%"
    }, {
      queue: false,
      duration: 500
    }).css("text-indent", "100%");
});

这种方法有些效果,但并非完全符合预期。

如果我在 div 中添加链接,它仍然会被动画化,但有时动画会中断,div 会崩溃,并且点击链接变得困难。

JSFiddle: http://jsfiddle.net/znxygpdw/

如何解决这个问题?


1
每次鼠标悬停在链接上时,都会触发一个mouseout事件。 - edc65
2个回答

4
在这种情况下最好使用“hover”功能:
//Sidbar Animations
$(".block").hover(function() {
    $(this)
    .animate({
        width: "90%"
    }, {
        queue: false,
        duration: 400
    }).css("text-indent", "0");
}, function() {
    $(this)
    .animate({
        width: "5%"
    }, {
        queue: false,
        duration: 500
    }).css("text-indent", "100%");
});

小提琴: https://jsfiddle.net/lmgonzalves/znxygpdw/1/

你是否正在使用回调函数来创建折叠动画? - Tachi
1
Hover函数接受两个参数,分别是'mouseenter'和'mouseleave'的别名。 - lmgonzalves

3

如上所述,最好使用hover功能。但是你的问题在于mouseout函数,当你将鼠标悬停在具有块状链接的位置时,事件会被触发。为了解决这个问题,请改用mouseleave函数。

//Sidbar Animations
    $(".block").mouseover(function() {
      $(this)
        .animate({
          width: "90%"
        }, {
          queue: false,
          duration: 400
        }).css("text-indent", "0");
    });
    $(".block").mouseleave(function() {
      $(this)
        .animate({
          width: "5%"
        }, {
          queue: false,
          duration: 500
        }).css("text-indent", "100%");
    });

http://jsfiddle.net/znxygpdw/4/


好的解释,顺便提一下在你的jsfiddle链接中你忘记把mouseout替换为mouseleave了。 - Tachi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接