实现页面中一个浮动球随着滚动条的滚动而滚动的效果

352 阅读1分钟

在vue2框架中,实现页面中一个浮动球随着滚动条的滚动而滚动,且最后它都会固定到在页面垂直居中的地方,还要有动画效果

可以通过以下步骤实现:

  1. 在页面中添加一个浮动球的元素,并设置其初始位置和样式。
  2. 监听窗口滚动事件,当滚动条滚动时,获取滚动条的位置,并将浮动球的位置设置为滚动条位置加上页面高度的一半。
  3. 使用CSS3动画来实现浮动球的滚动效果。可以使用transition或animation属性来实现动画效果。
  4. 当浮动球滚动到页面垂直居中的位置时,将其固定在该位置。

下面是一个简单的示例代码:

HTML部分:

<div class="float-ball">浮动球</div>

CSS部分:

.float-ball {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 50px;
  height: 50px;
  background-color: red;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  color: white;
  transition: all 0.3s ease;
}

JavaScript部分:

mounted() {
    // 监听了窗口的滚动事件
    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll() {
      // 获取当前窗口滚动条的位置
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
        // 获取浏览器可视区域高度
      const windowHeight = window.innerHeight;
      const ball = document.querySelector(".float-ball");
      // 获取节点高度
      const ballHeight = ball.offsetHeight;
      if (scrollTop + windowHeight > ballHeight / 2) {
        // 滚动的高度+窗口可视化区域高度的二分之一-浮动球高度的一半,就是浮动球在窗口垂直居中的位置
        ball.style.top = scrollTop + windowHeight / 2 - ballHeight / 2 + "px";
      }
    },
  },

在这个示例中,我们监听了窗口的滚动事件,并计算出浮动球的位置。当浮动球滚动到页面垂直居中的位置时,我们将其固定在该位置。同时,我们使用CSS3的transition属性来实现浮动球的滚动效果。