其他分享
首页 > 其他分享> > vue 实现 广告悬浮效果,并防抖性能优化

vue 实现 广告悬浮效果,并防抖性能优化

作者:互联网

节流防抖参考link:https://blog.csdn.net/zuorishu/article/details/93630578

<template>
  <img :src="aiUrl" class="ai-img" id="ai-img" />
</template>

<script>
export default {
  data() {
    return {
      timer: null,
      aiUrl: require("@/assets/img/home/ai.png")
    };
  },
  mounted() {
    // window.addEventListener("scroll", this.startMove, true);

    window.addEventListener("scroll", this.debounce(this.startMove, 100), true);
  },
  destroyed() {
    window.removeEventListener("scroll", this.startMove);
    clearInterval(this.timer);
  },
  methods: {
    debounce(fn, delay) {
      var timeout = null; // 创建一个标记用来存放定时器的返回值
      return function (e) {
        // 每当用户输入的时候把前一个 setTimeout clear 掉
        clearTimeout(timeout);
        // 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
        timeout = setTimeout(() => {
          fn.apply(this, arguments);
        }, delay);
      };
    },
    startMove() {
      var oDiv = document.getElementById("ai-img");
      var scrollTop = document.getElementById("popContainer").scrollTop;
      const iTarget = parseInt(
        (document.documentElement.clientHeight - oDiv.offsetHeight) / 2 +
          scrollTop
      );
      clearInterval(this.timer);
      this.timer = setInterval(function () {
        var oDiv = document.getElementById("ai-img");
        var speed = (iTarget - oDiv.offsetTop) / 5;
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

        if (oDiv.offsetTop == iTarget) {
          clearInterval(this.timer);
        } else {
          oDiv.style.top = oDiv.offsetTop + speed + "px";
        }
      }, 30);
    }
  }
};
</script>

<style lang="less">
.ai-img {
  position: absolute;
  bottom: 1.2rem;
  width: 1.34rem;
  z-index: 1000;
}
#contact-us-header {
  .ai-img {
    width: 1.34rem;
    position: absolute;
    bottom: 1rem;
  }
}
@media screen and (max-width: 1200px) {
  .ai-img {
    width: 1.34rem;
    position: absolute;
    bottom: 2rem;
  }
}
@media screen and (max-width: 979px) {
  .ai-img {
    width: 1.34rem;
    position: absolute;
    bottom: 2rem;
  }
}
@media screen and (max-width: 768px) {
  .ai-img {
    width: 1.34rem;
    position: absolute;
    bottom: 1rem;
  }
}
@media screen and (max-width: 690px) {
  .ai-img {
    display: none;
  }
}
@media screen and (max-width: 480px) {
  .ai-img {
    display: none;
  }
}
</style>

标签:防抖,vue,oDiv,img,悬浮,width,ai,rem,speed
来源: https://blog.csdn.net/qq_37167049/article/details/113766145