通过滑动方式切换显示/隐藏Div的动画

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

我只想在其父行内播放第二个 div 动画。现在第二个 div 正在移出行边界。我该如何处理这个问题?这是我第一次尝试动画。预先感谢。

function test(event) {
  var checkbox = document.getElementById('toggle');
  var firstDiv = document.getElementById('firstDiv');
  var secondDiv = document.getElementById('secondDiv');

  if (checkbox.checked) {
    secondDiv.classList.remove('col-lg-12')
    secondDiv.classList.remove('slide-in');
    secondDiv.classList.add('col-lg-7')
    secondDiv.classList.add('slide-out');
    //firstDiv.style.display = 'block';
    secondDiv.addEventListener('animationend', function() {
      firstDiv.style.display = 'block';
    }, {
      once: true
    });
  } else {
    firstDiv.style.display = 'none';
    secondDiv.classList.remove('slide-out');
    secondDiv.classList.remove('col-lg-7')
    secondDiv.classList.add('col-lg-12')
    secondDiv.classList.add('slide-in');
  }
}
.slide-in {
  animation: slide-in 3s forwards;
}

.slide-out {
  animation: slide-out 3s forwards;
}

@keyframes slide-in {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-out {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100%);
  }
}

.row {
  border: 1px solid black;
  /* Added row border */
  width: 500px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="row">
  <div id="firstDiv" style="background-color:palegreen" class="col-lg-5">first</div>
  <div id="secondDiv" style="background-color:yellow" class="col-lg-7">Second</div>
</div>
<div>
  <input type="checkbox" id="toggle" checked="checked" onchange="test(event)">
  <label for="toggle">Toggle Animation</label>
</div>

javascript html css css-animations
1个回答
0
投票

我已尝试解决您的问题。

您正在使用动画将 div 移动 100%。

.slide-in {
  animation: slide-in 3s forwards;
}

.slide-out {
  animation: slide-out 3s forwards;
}

@keyframes slide-in {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-out {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

.row {
  border: 1px solid black;
  /* Added row border */
  width: 500px;
}

或者你可以改变方向。

.slide-in {
  animation: slide-in 3s forwards;
}

.slide-out {
  animation: slide-out 3s forwards;
}

@keyframes slide-in {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slide-out {
  from {
    transform: translateY(-100%);
  }
  to {
    transform: translateY(0);
  }
}

.row {
  border: 1px solid black;
  /* Added row border */
  width: 500px;
}
© www.soinside.com 2019 - 2024. All rights reserved.