用漂亮的动画删除div

时间:2015-08-08 21:13:12

标签: javascript jquery css

我想删除带有精彩动画的div,但我不知道该怎么做。

所以我以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);
});

我看到了一个很好的例子here

但是当删除div时,她会被剪切掉,并且它们只是下一个div的动画。

有什么想法吗?

修改

最后解决:Jsfiddle

3 个答案:

答案 0 :(得分:8)

由于您删除了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/

答案 1 :(得分:4)

你可以这样做:

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

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

.notification {
    height: 40px;
    background: lightblue;
    margin: 2px;
}
&#13;
<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>
&#13;
&#13;
&#13;

这使用jQuery来动画而不是CSS。单击删除按钮时,它会向上滑动顶部栏,然后将其删除。

答案 2 :(得分:2)

我已用animation JsFiddle

解决了我的问题

感谢大家的帮助。