效果图如下:
长按之前:
长按之后:
若不想删除,在除删除按钮以外的地方单击即可。
下面是在react中的实现
//ThanksStyle.Item是要添加长按事件的对象
<ThanksStyle.Item key={index} onTouchStart={() => this.onItemTouchStart(index)} onTouchEnd={this.onItemTouchEnd} >
<ThanksStyle.Left>
<ThanksStyle.Title>{value.nickname}</ThanksStyle.Title>
<ThanksStyle.Time>{value.time}</ThanksStyle.Time>
</ThanksStyle.Left>
<ThanksStyle.Right>
<ThanksStyle.Love bg={love} />
<ThanksStyle.Num>{value.num}</ThanksStyle.Num>
{
// 删除按钮
<ThanksStyle.DeleteBtn
className={cn({ show: this.state.currentDeleteIndex === index })}
>
删除
</ThanksStyle.DeleteBtn>
}
</ThanksStyle.Right>
</ThanksStyle.Item>
其中onItemTouchStart(currentItem)和onItemTouchEnd函数的实现如下:
longPressInterval = 600; //longPressInterval长按的毫秒数
longPressItemTimeOut; //setTimeOut的返回值 为了清掉定时器
constructor(props) {
super(props);
this.state = {
currentDeleteIndex: -1 //currentDeleteIndex要出现删除按钮的当前Item的index,默认为-1
};
}
onItemTouchStart = currentItem => {
this.startTime = +new Date();
this.longPressItemTimeOut = setTimeout(
() => this.onLongPressItem(currentItem),
this.longPressInterval
);
};
onLongPressItem(currentItem) {
this.setState({
currentDeleteIndex: currentItem
});
}
onItemTouchEnd = () => {
this.endTime = +new Date();
const interval = this.endTime - this.startTime; //长按时长
if (interval < this.longPressInterval) { //按键时长<600,默认是点击事件
// TODO click操作 点击进入对应的Item
clearTimeout(this.longPressItemTimeOut);
this.setState({
currentDeleteIndex: -1
});
} else { //按键时长>600 长按
// TODO 长按操作
}
};
删除按钮对应的样式如下:
export const DeleteBtn = styled.div`
position: relative;
top: -0.57rem;
margin-left: 0.38rem;
width: 0.7rem;
height: 0.62rem;
line-height: 0.62rem;
font-size: 0.16rem;
background: #e94a14;
text-align: center;
color: #fff;
display: none;
&.show {
display: block;
}
`;
这样就可以实现长按操作啦~