Scroll上下滚动轮轮播实现

在这里插入图片描述
如上图,实现功能是,列表上下滚动轮播,用户鼠标移动到列表区域,滚动动画停止,鼠标移开滚动继续。
上述列子用REACT+CSS技术框架实现。
React:

import React, { useState, useRef, useEffect } from 'react';
import styles from './index.module.css';

export default function Scroll() {
  const [isScroll, setIsScroll] = useState(true); // 用于当鼠标移入时,滚动停止
  const scrollerRef = useRef(null);
  const timer = useRef(null);

  useEffect(() => {
    timer.current = setInterval(() => {
      if (isScroll && scrollerRef.current) {
        if (
          scrollerRef.current.scrollHeight - 1 <=
          scrollerRef.current.scrollTop + scrollerRef.current.clientHeight
        ) {
          setTimeout(() => {
            scrollerRef.current.scrollTop = 0;
          }, 500);
        }
        let rollSpeed =
          parseFloat((1 / window.devicePixelRatio).toFixed(2)) + 0.01; // + 0.01 为了保证 ratio >= 1
        if (window.navigator.userAgent.indexOf('Firefox') >= 0) {
          rollSpeed = 1.1;
        }
        scrollerRef.current.scrollTop += rollSpeed;
      }
    }, 50);
    return () => {
      timer.current && window.clearInterval(timer.current);
    };
  }, [isScroll]);

  return (
    <div className={styles.container}>
      <div
        className={styles.wrapper}
        ref={scrollerRef}
        onMouseEnter={() => setIsScroll(false)}
        onMouseLeave={() => setIsScroll(true)}
      >
        {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item, index) => (
          <div className={styles.item} key={index}>
            List-{item}
          </div>
        ))}
      </div>
    </div>
  );
}


css

.container {
  height: 300px;
  width: 300px;
  display: flex;
  .wrapper {
    width: 100%;
    overflow: auto;
    flex: 1;
    .item {
      width: 100%;
      height: 40px;
      box-sizing: border-box;
      padding: 0 10px;
      font-size: 18px;
      line-height: 38px;
      background-color: bisque;
      border-bottom: 1px solid #eee;
    }
    /* 滚动条相关属性配置 */
    &::-webkit-scrollbar {
      width: 3px;
      height: 3px;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 3px;
      background: #e3e3e3;
      -webkit-box-shadow: inset 0 0 5px #e3e3e3;
    }
    &::-webkit-scrollbar-track {
      background: #071d45;
      opacity: 0.8;
      border-radius: 3px;
    }
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值