04 react css上下浮动动画效果

html原生实现上下浮动

我们有一个导向箭头,需要微微浮动提示用户具体操作导向,用css去写,实现方法如下:

  • 首先创建一个dom元素,controller是包裹导向箭头的容器,img是导向箭头图片
  • css中创建动画,动画的快慢速度可以通过dom元素高度与animation中的秒数去调整
    完整代码:
.controller {
        position: absolute;
        width: 24px;
        height: 12px;
        z-index: 100;
        bottom: 20px;
        left: 50%;
        margin-left: -12px;
        -webkit-animation: bounce-down 1.6s linear infinite;
        animation: bounce-down 1.6s linear infinite;
 
        img {
             position: absolute;
        }
 }
 
@-webkit-keyframes bounce-down {
       25% {
            -webkit-transform: translateY(-4px);
       }
       50%, 100% {
            -webkit-transform: translateY(0);
       }
       75% {
            -webkit-transform: translateY(4px);
       }
}
 
@keyframes bounce-down {
        25% {
             transform: translateY(-4px);
        }
        50%, 100% {
             transform: translateY(0);
        }
        75% {
             transform: translateY(4px);
        }
}

react 实现上下浮动

思路分析

React点击事件实现滚动到指定页面位置,在react框架中通过函数组件的钩子函数useRef()

实现步骤

1.引入useRef

import React, { useEffect, useRef } from 'react';

2.在所属组件内定义—个变量

const downBtnRef = useRef(null)

3.在按钮上添加事件

<div className={styles.iconBox} ref={downBtnRef} onClick={toDown}>
     <DownOutlined />
</div>

4.定义点击事件

预期效果:平滑滚动

const toDown = () => {
    //在需要操作某个ref时候,通过downBtnRef.current,并且在整个项目中ref名唯一。
    if (downBtnRef.current) {
      console.log('downBtnRef.current', downBtnRef.current);
      window.scrollTo(0, downBtnRef.current.offsetHeight || 0)
    }
  }

实际效果:可以实现向下滑动一个屏幕的高度,但是我们需要平滑滚动

对window.scrollTo()进行了解:
  • 语法一:window.scrollTop(x,y) //x横坐标 y纵坐标
  • 例:window.scrollTop(0,1000)
  • 语法二:window.scrollTop(options)
  • 例:代码如下
 window.scrollTo({
    top: -560,
    left: 0,
    behavior: "smooth"
  });
在react中实现

点击事件的完整代码:

const toDown = () => {
    //在react中需要操作某个ref时候,通过downBtnRef.current,并且downBtnRef在整个项目中ref名唯一。
    if (downBtnRef.current) {
      console.log('downBtnRef.current', downBtnRef.current);
      window.scrollTo({
        top: downBtnRef.current.offsetTop,
        behavior: "smooth"
      });
    }
  }
效果图:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值