移动端网页div下滑消失、上滑出现(附带闪烁效果)

移动端网页div下滑消失、上滑出现(附带闪烁效果)_第1张图片

    <div :class = "IconShow ? 'mhomeIcon' : 'IconOff'">
      <img src="@/assets/news.svg" alt="">
    </div>

	// 距离顶部的距离
    const top = ref(0) 
    // 图标向上还是向下滑动
    const IconShow = ref(true)
    // 滑动监听, 注意如果只有document.documentElement.scrollTop这一个的话,安卓微信浏览器的滑动无法获取到。
    function handleScroll() {
      window.addEventListener('scroll', () => {
        top.value = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
      });
    }
    watch(
      () => top.value,
      (newValue, oldValue) => {
        if (newValue > 0) {
          // 新的值大于旧的值说明在向下滑动
          if (newValue > oldValue) {
            IconShow.value = false
          // 向上滑动,且相差大于5
          } else if (newValue < oldValue && (oldValue-newValue > 5)) { 
            IconShow.value = true
          }
        }
      },
      { immediate: true } 
    )
  onMounted(() => {
    // 执行滑动监听
    handleScroll();
  });

// ----------------------向上
.mhomeIcon {
  position: fixed;
  transition: all 1s ease-in-out 0s;  // 动画一共秒
  opacity: 1;   // 初试透明度100%
  top: 85%;   // 距离顶部85%
  right: 0.8rem;
  width: 2rem;
  height: 2rem;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 1rem;
  cursor: pointer;
  box-shadow: 0px 4px 10px 0px rgba(148,173,177,0.28);
  z-index: 100;
  transform-style: preserve-3d;  // 加这个是为了避免:after伪元素层级大于其他元素
  &>img {
    display: block;
    margin: 0 auto;
    z-index: 200;   // 图标层级最高
    width: 1.2rem;
    height: 1.4rem;
    margin-top: 0.4rem;
  }
}
.mhomeIcon:after {
  content: '';
  width: 2.6rem;
  height: 2.6rem;
  position: absolute;
  top: -0.3rem;
  left: -0.3rem;
  border-radius: 50%;
  animation: breath .6s linear .5s infinite alternate; // 呼吸动画实现
  background-color: rgba(43, 204, 204, 0.5);
  z-index: -100;  // 层级最低
  transform: translateZ(-10px);   // z轴负数
}
@keyframes breath { // 关键帧规则
  0%   { opacity: 0.5; }
  100% { opacity: 0; }
}
// ----------------------向下
.IconOff {
  position: fixed;
  right: 0.8rem;
  bottom: 0;
  transition: all 1s ease-in-out 0s;    // 动画1秒
  top: 100%;   // 距离顶部100%,也就跑出画面外了
  opacity: 0;   // 透明度0
  width: 2rem;
  height: 2rem;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 1rem;
  &>img {
    display: block;
    margin: 0 auto;
    width: 1.2rem;
    height: 1.4rem;
    margin-top: 0.4rem;  }
}

你可能感兴趣的:(Vue,vue.js)