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"
      });
    }
  }
效果图:

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐