首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在移动设备上的CSS或Javascript中平滑地设置动画高度

在移动设备上的CSS或JavaScript中平滑地设置动画高度,可以使用CSS的transition属性和JavaScript的requestAnimationFrame方法。以下是一个简单的示例:

  1. 使用CSS设置动画高度:
代码语言:css
复制
.box {
  width: 100px;
  height: 100px;
  background-color: red;
  transition: height 0.5s ease-in-out;
}

.box.expanded {
  height: 200px;
}
  1. 使用JavaScript控制动画高度:
代码语言:javascript
复制
const box = document.querySelector('.box');

function animateHeight() {
  const currentHeight = parseFloat(getComputedStyle(box).height);
  const targetHeight = box.classList.contains('expanded') ? 100 : 200;

  if (currentHeight === targetHeight) {
    return;
  }

  const startTime = performance.now();
  const duration = 500;

  function updateHeight() {
    const now = performance.now();
    const progress = Math.min((now - startTime) / duration, 1);
    const newHeight = currentHeight + (targetHeight - currentHeight) * progress;

    box.style.height = `${newHeight}px`;

    if (progress < 1) {
      requestAnimationFrame(updateHeight);
    }
  }

  requestAnimationFrame(updateHeight);
}

box.addEventListener('click', () => {
  box.classList.toggle('expanded');
  animateHeight();
});

在这个示例中,我们首先使用CSS设置了一个盒子的高度,并添加了一个transition属性,用于平滑地设置动画高度。然后,我们使用JavaScript监听盒子的点击事件,并在点击时切换盒子的高度。最后,我们使用requestAnimationFrame方法来实现动画效果。

这个示例可以在移动设备上平滑地设置动画高度,并且可以在多种浏览器和设备上运行。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券