移除列表项时的滑动过渡

问题描述 投票:0回答:1

自从我上次使用 CSS 以来已经有一段时间了。我在这方面遇到了麻烦。我有一个项目清单。当我点击十字时,它会从 DOM 中删除该项目。然而,我正在寻找的是让其余的项目在一个被移除时向上滑动

目前它只是根据需要删除项目,但会立即移动另一个项目以“填充空间”。我知道有一种方法可以通过 CSS 过渡来实现,但问题是如何......

var remove = function(id) {
  document.querySelector('#'+id).remove();
}
div {
  border: 1px solid grey;
  width: 100px;
  margin: auto;
  margin-bottom: 10px;
  text-align: center;
  padding: 10px
}
span {
  float: right;
  cursor: pointer;
}
<div id="one">One <span onclick="remove('one')">×</span></div>
<div id="two">Two <span onclick="remove('two')">×</span></div>
<div id="three">Three <span onclick="remove('three')">×</span></div>
<div id="four">Four <span onclick="remove('four')">×</span></div>

css css-animations css-transitions
1个回答
10
投票

像这样?

我添加了一个名为

closeSlide
的类,它将动画元素向上滑动。并且在过渡之后,通过设置一个定时器来移除它。

为了视觉美观,我已经将

overflow:hidden
添加到您的目标样式中,也可以使用
elem.style.overflow = 'hidden'
通过 JS 添加。但为了证明这一点,我将其添加到目标样式中,因为我想在启动关闭动画时避免任何可能的抖动。

var remove = function(id) {
  var elem = document.querySelector('#'+id);
  elem.className += 'closeSlide';
  setTimeout(function(){
    elem.remove();
  }, 200);
}
div {
  border: 1px solid grey;
  width: 100px;
  margin: auto;
  margin-bottom: 10px;
  text-align: center;
  padding: 10px;
  overflow:hidden;
}
span {
  float: right;
  cursor: pointer;
}
.closeSlide {
  margin-bottom:0;
  height:0px;
  padding-top:0;
  padding-bottom:0;
  transition: 0.2s all ease-out;
  /*Just reverse any spacing styling you've applied to make it **magically** disappear*/
}
<div id="one">One <span onclick="remove('one')">×</span></div>
<div id="two">Two <span onclick="remove('two')">×</span></div>
<div id="three">Three <span onclick="remove('three')">×</span></div>
<div id="four">Four <span onclick="remove('four')">×</span></div>

© www.soinside.com 2019 - 2024. All rights reserved.