滑動刪除,在不少APP軟件裏面能夠見到,好比淘寶的訂單列表,QQ微信的聊天記錄等等,今天就來看看JavaScript是如何實現這個功能的,之因此說是vue,主要是框架是vue啦,主要仍是JS+CSS部分。javascript
頁面就超級簡單咯,遍歷一個列表,添加touchstart
和touchend
事件,並添加刪除按鈕。若是滑動就添加move
類樣式,向左滑動60px
。css
<ul>
<li v-for="(item,index) in list" :class="{move:candelete.id==item.id}" @touchstart="touchStart(item)" @touchend="touchEnd(item)" >
{{item.text}}{{item.id}}
<div class="del" @click="deleteItem(index)">刪除</div>
</li>
</ul>
複製代碼
li{
background: #fdfdfd;
border-bottom: 1px solid #e1e1e1;
line-height: 40px;
position: relative;
transform: translateX(0);
transition: all .3s; /*滑動效果更生動*/
padding-left: 10px;
}
ul{
overflow-x: hidden; /*隱藏ul x軸的滾動條*/
}
li.move {
transform: translateX(-60px); /*滑動後x軸位移-60px,使其可見*/
}
.del {
position: absolute;
top: 0;
right: -1px;
z-index: 3;
width: 60px;
height: 100%;
text-align: center;
color: #fff;
background-color: #ff5b45;
transform: translateX(60px); /*默認x軸位移60px,使其隱藏*/
}
複製代碼
data() {
return {
// 數據
list: [{
id: 1,
text: '請左滑動刪除我吧'
},{
id: 2,
text: '請左滑動刪除我吧'
},{
id: 3,
text: '請左滑動刪除我吧'
},{
id: 4,
text: '請左滑動刪除我吧'
},{
id: 5,
text: '請左滑動刪除我吧'
},{
id: 6,
text: '請左滑動刪除我吧'
}],
clientNum: {}, // 記錄開始滑動(x1),結束滑動(x2)的鼠標指針的位置
candelete: {}, // 滑動的item
}
}
複製代碼
methods: {
/** * 刪除item * index是下標 */
deleteItem(index){
this.list.splice(index, 1)
// splice方法是刪除數組某條數據,或者向某個位置添加數據
},
touchStart(item) {
let touchs = event.changedTouches[0];
// 記錄開始滑動的鼠標位置
this.clientNum.x1 = touchs.pageX;
this.candelete = {};
},
touchEnd(item) {
let touchs = event.changedTouches[0];
// 記錄結束滑動的鼠標位置
this.clientNum.x2 = touchs.pageX;
this.candelete = {};
// 判斷滑動距離大於50,斷定爲滑動成功,不然失敗
if (
this.clientNum.x2 < this.clientNum.x1 &&
Math.abs(this.clientNum.x1) - Math.abs(this.clientNum.x2) > 50
) {
event.preventDefault();
this.candelete = item;
} else if (
this.clientNum.x2 > this.clientNum.x1 &&
Math.abs(this.clientNum.x2) - Math.abs(this.clientNum.x1) > 10
) {
event.preventDefault();
this.candelete = {};
}
}
}
複製代碼
就這樣愉快的結束了,是否是很簡單了?html
《ES6中Array數組你應該知道的操做》 《你對JavaScript的Array對象瞭解有多少?》 《CSS3中transition、transform傻傻分不清楚》vue