需求
默認(rèn)隱藏按鈕廉羔,左滑顯示按鈕溉痢,react實(shí)現(xiàn)。
實(shí)現(xiàn)思路
用絕對(duì)定位把元素設(shè)為負(fù)值以隱藏元素憋他,滑動(dòng)的時(shí)候适室,用translate改變按鈕的位置。
基礎(chǔ)知識(shí)
1.觸摸事件
touchstart事件:事件對(duì)象event举瑰,包含手指觸摸的位置
touchmove事件:事件對(duì)象event,包含手指滑動(dòng)的位置
touchend事件:事件對(duì)象event蔬螟,包含手指離開屏幕的位置
click事件:點(diǎn)擊事件此迅,和觸摸事件沖突
2. 觸摸事件和點(diǎn)擊事件的,先后觸發(fā)順序
在屏幕上點(diǎn)擊旧巾,先后觸發(fā)事件
在屏幕上滑動(dòng)耸序,先后觸發(fā)事件
注:從上圖中我們可以看出,click時(shí)間是在touchstart之后觸發(fā)的鲁猩】补郑滑動(dòng)手勢(shì)是不會(huì)觸發(fā)click事件的
react實(shí)現(xiàn)
樣式部分:
.role_li {
overflow: hidden;
@extend %flex;
justify-content: space-between;
align-items: center;
height: 150px;
padding-left: 42px;
padding-right: 36px;
position: relative;
.left {
width: 100%;
}
.role_name {
color: #000000;
font-weight: 600;
font-size: 28px;
}
.server_name {
color: #b6b6b6;
font-size: 24px;
}
.right {
@extend %flex-center;
position: absolute;
top: 0;
height: 100%;
width: 150px;
right: 0;
}
}
state = {
moveDistance: 0,
move: 0,
startX: 0,
distance: 70,
};
handleTouchstart = (e) => {
console.log("滑動(dòng)開始了");
console.log(e.targetTouches[0].clientX);
this.setState({
moveDistance: 0,
move: 0,
startX: e.targetTouches[0].clientX,
});
};
handleTouchMove = (e) => {
console.log(e.targetTouches[0].clientX);
console.log("滑動(dòng)了");
this.state.move = this.state.startX - e.targetTouches[0].clientX;
if (this.state.move > 0) {
// e.preventDefault();
this.state.moveDistance = Math.pow(this.state.move, 0.8);
this.setState({
moveDistance: this.state.move,
});
}
};
handleTouchEnd = (e) => {
console.log("滑動(dòng)結(jié)束了");
if (this.state.moveDistance > this.state.distance / 2) {
this.setState({
moveDistance: this.state.distance,
});
} else {
this.setState({
moveDistance: 0,
});
}
};
<ul className="role_list">
<li className="role_li">
<div
className="left"
onTouchEnd={this.handleTouchEnd}
onTouchMove={this.handleTouchMove}
onTouchStart={this.handleTouchstart}
>
<p className="role_name">澈澈澈澈澈兒</p>
<p className="server_name">iOS-QQ2服-萬(wàn)水依山</p>
</div>
<div
className="right"
style={{
width: `${this.state.distance}px`,
right: `${-this.state.distance}px`,
transition: `300ms`,
transform: `translate3d(${-this.state
.moveDistance}px,0, 0)`,
}}
>
<span className="del_ico"></span>
</div>
</li>
</ul>