廢話不多少,直接上代碼
# index.js
import styles from './index.less';
import React, { Component } from 'react';
class PlayProcess extends Component {
constructor(props) {
super(props);
this.state = {
autoPaly: false
}
}
handleClick(e){
let sepUnit = 24;
// 進度等格劃分
const len = this.line.clientWidth / sepUnit; //每等份寬度
// const windowWidth = window.innerWidth - this.line.clientWidth - this.line.offsetLeft;//計算屏幕寬度除去進度條后還剩余寬度,因為offsetLeft算得是相對最近position非static的父節(jié)點的偏差,event中坐標是相對整個window的
// let lineWidth;// 進度條有效寬度
// if(windowWidth > 0){
// lineWidth = e.pageX - this.line.offsetLeft - windowWidth;
// }else{
// lineWidth = e.pageX - this.line.offsetLeft;
// }
// const innerWidth = Math.round(lineWidth / len);// 份數(shù)計算
// //轉(zhuǎn)百分比
// this.innerLine.style.width = ( 100 / sepUnit ) * innerWidth + '%';
this.innerLine.style.width = 100 * ( e.pageX - this.line.offsetLeft ) / this.line.clientWidth + '%';
}
handleMouseDown(){
this.setState({
drag: true
});
}
handleMouseMove(e){
if(this.state.drag){
this.innerLine.style.width = 100 * ( e.pageX - this.line.offsetLeft ) / this.line.clientWidth + '%';
}
}
handleMouseUp(e){
this.setState({
drag: false
});
}
handleMouseLeave(){
this.setState({
drag: false
});
}
togglePlay(){
this.setState({autoPaly: !this.state.autoPaly});
}
render() {
return (
<div
ref={ play => {
this.play = play
}}
style={this.props.style ? this.props.style: {}}
className={styles.container}>
<span
onClick={e => {
this.togglePlay();
}}
className={styles.playButton}>
{this.state.autoPaly
? <span>pause</span>
: <span>play</span>
}
</span>
<span
onClick={e => this.handleClick(e)}
onMouseMove={e => this.handleMouseMove(e)}
onMouseUp={e => this.handleMouseUp(e)}
onMouseLeave={e => this.handleMouseLeave(e)}
ref={line => {
this.line = line
}}
className={styles.lineWrap}>
<span
ref={innerLine => {
this.innerLine = innerLine
}}
className={styles.lineInner}>
<span
onMouseDown={e => this.handleMouseDown(e)}
ref={dot => {
this.dot = dot
}}
className={styles.lineDot}></span>
</span>
</span>
</div>
);
}
}
export default PlayProcess;
.container {
width: 100%;
height: 30px;
padding: 5px;
.playButton {
}
.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%;
}
}
}
}