网站首页 > 技术文章 正文
前几天有给大家分享一个Vue自定义滚动条组件VScroll。今天再分享一个最新开发的React PC端模拟滚动条组件RScroll。
rscroll 一款基于react.js构建的超小巧自定义桌面端美化滚动条。支持原生滚动条、自动隐藏、滚动条尺寸/层级/颜色等功能。
如上图:支持垂直/水平滚动条。
功能及效果和之前VScroll保持一致。在开发支持参考借鉴了el-scrollbar等组件设计思想。
调用非常简单,只需<RScroll></RScroll>包裹住内容即可快速生成一个漂亮的滚动条。
引入组件
// 引入滚动条组件RScroll
import RScroll from './components/rscroll'快速使用
<RScroll native>
    <img src="/logo.svg" style={{maxWidth: '100%'}} />
    <p>这里是内容信息!这里是内容信息!这里是内容信息!</p>
</RScroll>
<RScroll autohide={true} size="10" color="#09f">
    <img src="/logo.svg" style={{maxWidth: '100%'}} />
    <p>这里是内容信息!这里是内容信息!这里是内容信息!</p>
    <p>这里是内容信息!这里是内容信息!这里是内容信息!</p>
    <p>这里是内容信息!这里是内容信息!这里是内容信息!</p>
</RScroll>编码实现
在components目录下新建rscroll目录,并创建index.js页面。
rscroll滚动条模板
render() {
    return (
        <div className="vui__scrollbar" ref={el => this.$ref__box = el} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
            <div className={domUtils.classNames('vscroll__wrap', {'native': prop.native})} ref={el => this.$ref__wrap = el} onScroll={this.handleScroll}>
                <div className="vscroll__view">
                    {prop.children}
                </div>
            </div>
            {/* 滚动条 */}
            <div className={domUtils.classNames('vscroll__bar vertical', {'ishide': !opt.isShow})} onMouseDown={this.handleClickTrack.bind(this, 0)} style={{...barYStyle}}>
                <div className="vscroll__thumb" ref={el => this.$ref__barY = el} onMouseDown={this.handleDragThumb.bind(this, 0)} style={{background: prop.color, height: opt.barHeight+'px'}}></div>
            </div>
            <div className={domUtils.classNames('vscroll__bar horizontal', {'ishide': !opt.isShow})} onMouseDown={this.handleClickTrack.bind(this, 1)} style={{...barXStyle}}>
                <div className="vscroll__thumb" ref={el => this.$ref__barX = el} onMouseDown={this.handleDragThumb.bind(this, 1)} style={{background: prop.color, width: opt.barWidth+'px'}}></div>
            </div>
        </div>
    )
}react监听元素/DOM尺寸变化。由于react不像vue可以自定义指令directives,只能使用componentDidUpdate来监听。
componentDidUpdate(preProps, preState) {
    // 监听内层view DOM尺寸变化
    let $view = this.$ref__wrap.querySelector('.vscroll__view')
    const viewStyle = $view.currentStyle ? $view.currentStyle : document.defaultView.getComputedStyle($view, null);
    if(preState.$viewWidth !== viewStyle.width || preState.$viewHeight !== viewStyle.height) {
        this.setState({ $viewWidth: viewStyle.width, $viewHeight: viewStyle.height })
        this.updated()
    }
}/**
 * ReactJs|Next.js自定义滚动条组件RScroll
 */
import React from 'react'
class RScroll extends React.Component {
    /**
     * 默认配置
     */
    static defaultProps = {
        // 是否显示原生滚动条
        native: false,
        // 鼠标滑出是否自动隐藏滚动条
        autohide: false,
        // 自定义滚动条大小
        size: '',
        // 自定义滚动条颜色
        color: '',
        // 滚动条层级
        zIndex: null
    }
    constructor(props) {
        super(props)
        this.state = {
            barWidth: 0,                    // 滚动条宽度
            barHeight: 0,                   // 滚动条高度
            ratioX: 1,                      // 滚动条水平偏移率
            ratioY: 1,                      // 滚动条垂直偏移率
            isTaped: false,                 // 鼠标光标是否按住滚动条
            isHover: false,                 // 鼠标光标是否悬停在滚动区
            isShow: !this.props.autohide,   // 是否显示滚动条
            $viewWidth: null,
            $viewHeight: null,
        }
    }
    // 鼠标滑入
    handleMouseEnter = () => {
        this.setState({
            isHover: true, isShow: true
        })
        this.updated()
    }
    // 鼠标滑出
    handleMouseLeave = () => {
        const { isTaped } = this.state
        this.setState({ isHover: false })
        this.setState({ isShow: false })
    }
    // 拖动滚动条
    handleDragThumb = (index, e) => {
        let _this = this
        this.setState({ isTaped: true })
        const { ratioX, ratioY } = this.state
        let c = {}
        // 阻止默认事件
        domUtils.isIE() ? (e.returnValue = false, e.cancelBubble = true) : (e.stopPropagation(), e.preventDefault())
        document.onselectstart = () => false
        if(index == 0) {
            c.dragY = true
            c.clientY = e.clientY
        }else {
            c.dragX = true
            c.clientX = e.clientX
        }
        domUtils.on(document, 'mousemove', function(evt) {
            if(_this.state.isTaped) {
                if(c.dragY) {
                    _this.$ref__wrap.scrollTop += (evt.clientY - c.clientY) * ratioY
                    _this.$ref__barY.style.transform = `translateY(${_this.$ref__wrap.scrollTop / ratioY}px)`
                }
                if(c.dragX) {
                    _this.$ref__wrap.scrollLeft += (evt.clientX - c.clientX) * ratioX
                    _this.$ref__barX.style.transform = `translateX(${_this.$ref__wrap.scrollLeft / ratioX})`
                }
            }
        })
        domUtils.on(document, 'mouseup', function() {
            _this.setState({ isTaped: false })
            document.onmouseup = null
            document.onselectstart = null
            if(!_this.state.isHover && _this.props.autohide) {
                _this.setState({ isShow: false })
            }
        })
    }
    // 点击滚动槽
    handleClickTrack = (index, e) => {
        // ...
    }
    // 更新滚动区
    updated = () => {
        if(this.props.native) return
        let c = {}
        let barSize = domUtils.getScrollBarSize()
        // 垂直滚动条
        if(this.$ref__wrap.scrollHeight > this.$ref__wrap.offsetHeight) {
            c.barHeight = this.$ref__box.offsetHeight **2 / this.$ref__wrap.scrollHeight
            c.ratioY = (this.$ref__wrap.scrollHeight - this.$ref__box.offsetHeight) / (this.$ref__box.offsetHeight - c.barHeight)
            this.$ref__barY.style.transform = `translateY(${this.$ref__wrap.scrollTop / c.ratioY}px)`
            // 隐藏系统滚动条
            if(barSize) {
                this.$ref__wrap.style.marginRight = -barSize + 'px'
            }
        }else {
            c.barHeight = 0
            this.$ref__barY.style.transform = ''
            this.$ref__wrap.style.marginRight = ''
        }
        // 水平滚动条
        ...
    }
    // 鼠标滚动
    handleScroll = (e) => {
        const { onScroll } = this.props
        typeof onScroll === 'function' && onScroll.call(this, e)
        this.updated()
    }
    render() {
        return (
            // ...
        )
    }
}
export default RScroll<RScroll onScroll={this.handleScroll}>
    <img src="/logo.svg" style={{height: 180, marginRight: 10}} />
    <br />
    <p><img src="/logo.svg" style={{height: 250}} /></p>
    <p>这里是内容信息!这里是内容信息!这里是内容信息!</p>
</RScroll>
// 监听滚动事件
handleScroll = (e) => {
    let _scrollTop = e.target.scrollTop
    let _scrollStatus
    // 判断滚动状态
    if(e.target.scrollTop == 0) {
        _scrollStatus = '滚到至顶部'
    } else if(e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight) {
        _scrollStatus = '滚动至底部'
    }else {
        _scrollStatus = '正滚动中..'
    }
    this.setState({
        scrollTop: _scrollTop,
        scrollStatus: _scrollStatus
    })
}好了,以上就是基于react.js开发自定义美化滚动条组件。希望大家能喜欢~~
猜你喜欢
- 2025-08-01 装饰材料——JS防水涂料,施工必知!
 - 2025-08-01 p5.js 圆弧的用法
 - 2025-08-01 通过JS获取你当前的网络状况?建议大家学一学~
 - 2025-08-01 JavaScript 事件循环机制详解
 - 2025-05-09 js防水涂料的使用方法(js防水涂料的防水作用机理)
 - 2025-05-09 JavaScript 展开data 是什么语法(js实现展开收缩)
 - 2025-05-09 JavaScript 可选链操作符详解(javascript选项)
 - 2025-05-09 Express.js 创建Node.js Web应用(express搭建)
 - 2025-05-09 JavaScript 强制回流问题及优化方案
 - 2025-05-09 OS.js – 开源的 Web OS 系统,赶快来体验
 
- 最近发表
 - 
- 聊一下 gRPC 的 C++ 异步编程_grpc 异步流模式
 - [原创首发]安全日志管理中心实战(3)——开源NIDS之suricata部署
 - 超详细手把手搭建在ubuntu系统的FFmpeg环境
 - Nginx运维之路(Docker多段构建新版本并增加第三方模
 - 92.1K小星星,一款开源免费的远程桌面,让你告别付费远程控制!
 - Go 人脸识别教程_piwigo人脸识别
 - 安卓手机安装Termux——搭建移动服务器
 - ubuntu 安装开发环境(c/c++ 15)_ubuntu安装c++编译器
 - Rust开发环境搭建指南:从安装到镜像配置的零坑实践
 - Windows系统安装VirtualBox构造本地Linux开发环境
 
 
- 标签列表
 - 
- cmd/c (90)
 - c++中::是什么意思 (84)
 - 标签用于 (71)
 - 主键只能有一个吗 (77)
 - c#console.writeline不显示 (95)
 - pythoncase语句 (88)
 - es6includes (74)
 - sqlset (76)
 - apt-getinstall-y (100)
 - node_modules怎么生成 (87)
 - chromepost (71)
 - flexdirection (73)
 - c++int转char (80)
 - mysqlany_value (79)
 - static函数和普通函数 (84)
 - el-date-picker开始日期早于结束日期 (76)
 - js判断是否是json字符串 (75)
 - c语言min函数头文件 (77)
 - asynccallback (87)
 - localstorage.removeitem (77)
 - vector线程安全吗 (73)
 - java (73)
 - js数组插入 (83)
 - mac安装java (72)
 - 无效的列索引 (74)
 
 
