移除带有动画效果的 div 元素

4

我希望能够用一个很棒的动画效果来移除

元素,但是我不知道该怎么做。

因此,我创建了一个fiddle作为示例:

HTML

<h2>What I have</h2>
<div class='test'>1</div>
<div class='test'>2</div>
<div class='test'>3</div>
<div class='test'>4</div>
<div class='test'>5</div>

<h2>What I Want</h2>
<div class='test2'>1</div>
<div class='test2'>2</div>
<div class='test2'>3</div>
<div class='test2'>4</div>
<div class='test2'>5</div>

CSS

div.test, div.test2 {
    display:inline-block;
    padding: 20px;
    margin:5px;

    border:1px solid black;

    -webkit-transition: all .5s;
    -moz-transition: all .5s;
    -ms-transition: all .5s;
    -o-transition: all .5s;
    transition: all .5s;
}

JS

$('div.test').on('click', function() {
   $(this).remove();
});

$('div.test2').on('click', function() {
    // I don't want to change opacity or padding...
    // I just want to remove with animation like this:
    $(this).css('width','0px').css('padding','0px');
    $(this).css('opacity',0);
});

我在这里看到一个很好的例子(链接)

但是当一个div被移除时,她会被切断,并且它们只为下一个div进行动画。

有什么想法吗?

编辑

最终解决方案:Jsfiddle


4
你可以回答自己的问题,无需在问题中编辑你的解决方案。 - user3117575
3个回答

9

由于您删除了element,因此它不能再进行animated。 您可以通过类进行动画处理,并在transitionend上删除元素。 例如:

.animate
{
    height: 0px;//or anything you need
    transition: height 1s;
}



$('#delete').click(function (e) {
        //instead of remove you add a class.
        $(".notification:first-child").addClass('animate');
    });
$('.notification').on('transitionend', function(e){
    //when transition is finished you remove the element.
    $(e.target).remove()
});

http://jsfiddle.net/nawkufh1/


6

我用JsFiddle解决了我的问题,问题与animation有关。非常感谢大家的帮助。


5
您可以像这样做:

$('#delete').click(function (e) {
  $(".notification:first-child").slideUp(function() {
    $(this).remove();
  });
});

$('#add').click(function (e) {
  $(".notifications").append("<div class='notification'></div>");
});
.notifications {
    left: 0px;
    top: 0px;
    width: 400px;
    height: 300px;
    position: relative;
    border: solid 1px green;
}

.notification {
    height: 40px;
    background: lightblue;
    margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="button" id="delete">delete</button>
<button type="button" id="add">add</button>
<div class="notifications">
  <div class="notification"></div>
  <div class="notification"></div>
  <div class="notification"></div>
  <div class="notification"></div>
</div>

这里使用jQuery来实现动画效果,而不是使用CSS。当点击删除按钮时,它会将顶部的条形菜单向上滑动,然后将其删除。


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