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

在这里插入图片描述

    <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;  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值