react 实现可播放的进度条

本文介绍了一个自定义音视频播放器进度条的设计与实现,包括点击播放、暂停、进度拖拽等功能。通过计算点击位置及使用定时器实现进度更新,支持不同屏幕尺寸下的适配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现的效果图如下:


如果所示,点击播放按钮可以播放,进度条表示进度


功能描述:

1. 点击播放按钮可以播放,进度条表示进度

2. 点击暂停,进度条停止变化

3. 可点击圆点,进行进度拖拽

4. 点击进度条可调节进度

以下是render部分代码:

<div className="play" ref={play => { this.play = play; }}>
          <span className="palyButton" onClick={this.handlePlay}><Icon type="caret-right" style={{ display: this.state.autoPlay ? 'none' : 'inline-block' }} /><Icon type="pause" style={{ display: this.state.autoPlay ? 'inline-block' : 'none' }} /></span>
          <span className="lineWrap" onMouseMove={this.handleMouseMove} onMouseUp={this.handleMouseUp} onMouseLeave={this.handleMouseUp} onClick={this.clcikLine} ref={line => { this.line = line; }}>
            <span className="lineInner" ref={inner => { this.inner = inner; }}>
              <span className="lineDot" onMouseDown={this.handleMouseDown} ref={dot => { this.dot = dot; }} />
            </span>
          </span>
        </div>

定义一个最大的div来包裹播放按钮和进度条:

播放按钮是两个antd的icon,通过state中的autoPlay来控制显示哪一个icon

进度条的中定义一个外span,是进度条的总长度,在这个span里定义一个span,是中间的滑块,再定义一个span是可拖拽的圆点

以下是这部分的css样式代码,只要小圆点使用的绝对定位:

  .play{
    width: 100%;
    height: 30%;
    padding: 0 40px;
    margin-top: 15px;
    .palyButton{
      margin-right: 22px;
      cursor: pointer;
      color: #1DDD92;
      font-size: 20px;
      i:last-child{
        font-weight: bold;
      }
    }
    .lineWrap{
      width: 95%;
      height: 14px;
      background-color: #2A2F4D;
      display: inline-block;
      cursor: pointer;
      .lineInner{
        width: 10%;
        height: 100%;
        display: inline-block;
        background-color: #1DDD92;
        position: relative;
        .lineDot{
          position: absolute;
          top: -3px;
          right: -10px;
          width: 20px;
          height: 20px;
          display: inline-block;
          background-color: #1DDD92;
          border: 1px solid #fff;
          border-radius: 50%;
        }
      }
    }
  }

功能实现的思想:

1. 点击进度条可以实现进度调整

原理:点击进度条获取点击事件的pageX属性,然后通过减去进度条左边的margin来计算点击的进度条的位置,因为整个页面的左边有一个tab切换,这个tab切换可以被隐藏,所以整个进度条的宽度是不定的,所以进度条的滑块要使用百分比来实现,保证在进度条总宽度变化时滑块的宽度按比例变化:

  clcikLine = e => {
    const len = this.line.clientWidth / 24;
    // 将整个进度条分为24份
    const windowWidth = window.innerWidth - this.line.clientWidth - this.line.offsetLeft - 20;
    let lineWidth;
    if (windowWidth > 240) {
      // 当导航显示时,计算整个滑块的宽度要减去导航的宽度240px
      lineWidth = e.pageX - this.line.offsetLeft - 240;
    } else {
      lineWidth = e.pageX - this.line.offsetLeft;
    }
    // 将最终的滑块宽度按百分比进行转换
    const innerWidth = Math.round(lineWidth / len);
    this.inner.style.width = 100 / 24 * innerWidth + '%';
  }

2. 点击播放,进度增加,点击暂停,进度停止

  handlePlay = () => {
    // 设置播放按钮
    this.setState({
      autoPlay: !this.state.autoPlay,
    });
    // 清楚定时器
    clearInterval(this.timer);

    setTimeout(() => {
      if (this.state.autoPlay) {
        const wrapWidth = this.line.clientWidth;
        const innerWidth = this.inner.clientWidth;
        if (innerWidth < wrapWidth) {
          this.timer = setInterval(() => {
            // 设置定时器,每1000毫秒执行一次,每1000毫秒滑块长度增加进度条的1%长度
            this.inner.style.width = Math.round(this.inner.clientWidth / this.line.clientWidth * 100) + 1 + '%';
            // 每次获得的增加的百分比长度都进行四舍五入
            if (this.inner.clientWidth >= this.line.clientWidth) {
              // 当滑块的长度大于等于进度条的长度时,清楚定时器,并且关闭播放按钮
              clearInterval(this.timer);
              this.setState({
                autoPlay: false
              });
            }
          }, 1000);
        } else {
          // 当滑块宽度大于进度条宽度时,点击播放按钮,延时1000毫秒自动关闭播放按钮
          setTimeout(() => {
            this.setState({
              autoPlay: false
            });
          }, 1000);
        }
      }
    }, 20);
  }

3. 圆点可以拖拽,调整进度条进度

这个功能中,使用了四个事件,分别是:onMouseMove、onMouseUp、onMouseLeave放在进度条上,onMouseDown放在可拖拽的圆点上。

  handleMouseDown = e => {
    // 鼠标按下时打开可拖功能
    this.setState({
      drag: true,
    });
  }

  handleMouseMove = e => {
    // 当可拖拽功能打开时
    if (this.state.drag) {
      // 滑块宽度小于进度条宽度或大于0时
      if (this.inner.clientWidth <= this.line.clientWidth || this.inner.clientWidth <= 0) {
        // 将进度条分为200份
        const len = this.line.clientWidth / 200;
        // 判断导航是否隐藏
        const windowWidth = window.innerWidth - this.line.clientWidth - this.line.offsetLeft - 20;
        let lineWidth;
        if (windowWidth > 240) {
          // 导航未隐藏
          lineWidth = e.pageX - this.line.offsetLeft - 240;
        } else {
          // 导航隐藏
          lineWidth = e.pageX - this.line.offsetLeft;
        }
        const innerWidth = Math.round(lineWidth / len);
        // 滑块宽度每次增加或减少0.5%的宽度
        this.inner.style.width = 0.5 * innerWidth + '%';
      }
    }
  }

  handleMouseUp = e => {
    // 当鼠标放开或者离开进度条时关闭拖拽功能
    this.setState({
      drag: false,
    });
  }
以上基本实现了这个功能,播放这一块还会再加东西,后期再加入
### 如何使用 React 实现带有柱状进度条的排行榜组件 为了创建一个带有柱状进度条的排行榜组件,可以利用 `react-animated-number` 库来实现平滑变化的效果[^1]。下面是一个完整的例子,展示了如何构建这样的组件。 #### 创建排行榜项组件 首先定义单个排行项目的组件,该组件接收排名、名称以及分数作为属性,并渲染出对应的柱状进度条: ```jsx import React from 'react'; import AnimatedNumber from 'react-animated-number'; const RankItem = ({ rank, name, score }) => { const maxScore = 100; // 设定最大分值以便计算宽度比例 return ( <div className="rank-item"> <span>{rank}</span> <p>{name}</p> <div className="progress-bar-container"> <div className="progress-bar" style={{ width: `${(score / maxScore) * 100}%` }} > <AnimatedNumber value={score} formatValue={(v) => v.toFixed()} /> </div> </div> </div> ); }; ``` 此部分代码实现了每个排行榜成员的具体表现形式,其中包含了动态更新得分的功能。 #### 构建排行榜列表容器 接着编写父级组件负责管理整个排行榜的数据源并迭代生成子组件实例: ```jsx import React from 'react'; import './RankList.css'; // 自定义CSS样式文件路径 import RankItem from './RankItem'; class RankList extends React.Component { constructor(props){ super(props); this.state = { ranks: [ { id: 1, name: "Alice", score: 85 }, { id: 2, name: "Bob", score: 92 }, { id: 3, name: "Charlie", score: 76 } ] }; } render(){ return( <ul className="rank-list"> {this.state.ranks.map((item, index)=><li key={index}><RankItem {...item} rank={`${index + 1}.`} /></li>)} </ul> ) } } export default RankList; ``` 这段代码片段中,`RankList` 类型继承自 `React.Component` 并初始化了一些模拟数据,在实际应用里这些信息应该来自服务器接口或其他持久化存储位置。 #### 添加 CSS 样式美化界面 最后为上述 HTML 结构添加必要的样式使其看起来更美观: ```css /* 文件名:RankList.css */ .rank-list{ list-style-type:none; padding-left:0px; } .rank-item{ display:flex; align-items:center; margin-bottom:1em; } .progress-bar-container{ flex-grow:1; height:.5rem; background-color:#eaeaea; border-radius:.25rem; overflow:hidden; margin-left:auto; } .progress-bar{ float:left; height:inherit; line-height:normal; text-align:right; color:white; font-weight:bold; transition-property:width; transition-duration:.4s; box-shadow:inset 0 .1rem .2rem rgba(0,0,0,.1), inset 0 -.1rem .2rem rgba(0,0,0,.1); } @media (min-width:768px){ .rank-item p{font-size:larger;} } ``` 以上就是基于 React 的简单版带柱状进度条的排行榜组件的设计思路与具体实现方式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值