按住CTRL多选,按住shift连选的实现

时间:2021-09-19 10:45:06
<tr class="address" v-for="(counts, index) in counts" :key="index" @click="trSelect(index)" :class="rowsSelect.indexOf(index) != -1 ? 'selectTr' : ''"></tr>
document.onkeydown =  (e) => {
if (!this.keyCode) {
if (window.event) {
this.keyCode = event.keyCode;
} else if (e.which) {
this.keyCode = e.which;
} }
};
document.onkeyup = () => {
if (this.keyCode) {
this.keyCode = undefined;
}
};
trSelect(index) {
switch (this.keyCode) {
case 17://ctrl
this.isCtrl = true;
if (this.rowsSelect.indexOf(index) != -1) {
this.rowsSelect.splice(index, 1);
} else {
this.rowsSelect.push(index);
}
this.startIndex = index;
break;
case 16://shift
if (!this.isCtrl && this.rowsSelect.length == 0) {
this.rowsSelect.push(index);
this.startIndex = index;
return;
}
let start, end;
if (this.startIndex < index) {
start = this. startIndex;
end = index;
} else {
start = index;
end = this.startIndex;
}
this.rowsSelect = []; for (let k = start; k <= end; k++) {
this.rowsSelect.push(k);
}
this.isCtrl = false;
break;
default:
this.rowsSelect = [index];
this.isCtrl = false;
this.startIndex = index;
break;
} }