CSS 滚动时更改 CSS transform:突兀运动与平滑运动

在本文中,我们将介绍如何在滚动时更改 CSS transform,以实现突兀运动和平滑运动两种效果。

阅读更多:CSS 教程

1. 突兀运动

突兀运动是指在滚动过程中,元素的变化呈现出不连续、不平滑的效果。这种效果通常会给人一种跳跃感,可能会让用户感到不舒服。

要实现突兀运动,我们可以使用 scroll 事件和计算元素的位置来实时更新元素的样式。

/* HTML */
<div id="box"></div>

/* CSS */
#box {
  width: 100px;
  height: 100px;
  background: red;
  transition: transform 0.3s; /* 添加过渡效果 */
}

/* JavaScript */
window.addEventListener('scroll', function() {
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  var box = document.getElementById('box');
  box.style.transform = 'translateY(' + scrollTop + 'px)';
});

在上面的示例中,当页面滚动时,scroll 事件被触发,监听该事件后,我们可以通过 scrollTop 属性获取当前页面滚动的距离。然后,我们将这个距离应用到 transform 属性上,使元素在垂直方向上进行偏移,从而实现突兀的运动效果。

2. 平滑运动

与突兀运动相反,平滑运动是指在滚动过程中,元素的变化呈现出流畅、平缓的效果。这种效果通常会给人一种自然的感觉,更加符合用户的期望。

要实现平滑运动,我们需要借助 CSS 的 transition 属性和 requestAnimationFrame 方法。

/* HTML */
<div id="box"></div>

/* CSS */
#box {
  width: 100px;
  height: 100px;
  background: red;
  transition: transform 0.3s; /* 添加过渡效果 */
}

/* JavaScript */
var box = document.getElementById('box');
var initialPosition = box.getBoundingClientRect().top; // 获取元素初始位置
var lastPosition = initialPosition;

function smoothMove() {
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  var currentPosition = box.getBoundingClientRect().top;

  // 计算元素的偏移量
  var deltaY = (currentPosition - lastPosition) * -1;

  // 更新元素的样式
  box.style.transform = 'translateY(' + (scrollTop + deltaY) + 'px)';

  lastPosition = currentPosition;

  // 使用 requestAnimationFrame 实现动画
  requestAnimationFrame(smoothMove);
}

window.addEventListener('scroll', smoothMove);

在上述代码中,我们先获取了元素的初始位置 initialPosition,然后在滚动时通过 getBoundingClientRect() 方法计算出元素当前的位置 currentPosition。接着,我们使用这两个位置的差值 deltaY 来更新元素的样式。最后,我们使用 requestAnimationFrame 方法实现平滑的动画效果。在 scroll 事件中调用 smoothMove() 方法,这样就可以在滚动时平滑地改变元素的位置。

总结

本文介绍了如何在滚动时更改 CSS transform,以实现突兀运动和平滑运动两种效果。突兀运动使用 scroll 事件和元素位置计算来实时更新样式,而平滑运动则利用 CSS 的 transition 属性和 requestAnimationFrame 方法来实现流畅的动画效果。通过合理运用这些技巧,我们可以根据具体的需求给用户带来更好的滚动体验。

最后修改:2024 年 05 月 30 日
如果觉得我的文章对你有用,请随意赞赏