在网上找到bootstra-table按住shift实现多选的思路后,进行改进,实现批量选中/批量取消选中,批量选中后取消部分选中并保留剩下选中项,向上/向下批量操作。
参考地址:https://blog.csdn.net/qq_36360308/article/details/115604059
// 按住shift一次选中多个数据行实现批量选中/批量取消选中
function shiftMultiSelectTableRows(){
// shift多选
let mode = ""; // 模式:批量选中/批量取消选中
let type = ""; // 当前选中行的操作类型:选中/取消选中
let lastStart = null; // 上一次记录的起点
let lastEnd = null; // 上一次记录的终点
let nowEnd = null; // 批量选中后部分取消时,记录的实际选中项的终点
let flag = true;
$(document).on("change", ".bs-checkbox input", function(e) {
if(mode == ""){
if($(this).is(':checked') && flag) mode = "batchCheck";
if(!$(this).is(':checked') && flag) mode = "batchUncheck";
}
if(mode == "batchCheck"){
if ($(this).is(':checked') && flag){
type = "check";
if (lastEnd != null) lastStart = lastEnd;
lastEnd = $(this).attr("data-index");
}else if (!$(this).is(':checked')){
type = "uncheck";
nowEnd = $(this).attr("data-index");
}
}else if(mode == "batchUncheck"){
if (!$(this).is(':checked') && flag){
type = "uncheck";
if (lastEnd != null) lastStart = lastEnd;
lastEnd = $(this).attr("data-index");
}
}
});
//让上面方法先执行完
$(document).mousedown(function(e) {
if (e.shiftKey) {
setTimeout(function (){
if(mode == "batchCheck"){
if(type == "check"){
if (lastStart != null && lastEnd != null){
let agentNum = null; // 中间变量,支持向上/向下批量选择
if(lastStart > lastEnd){
agentNum = lastStart;
lastStart = lastEnd;
lastEnd = agentNum;
}
flag = false;
for(let i = parseInt(lastStart)+1;i<parseInt(lastEnd);i++){
if(!$("input[data-index='"+i+"']").is(":checked")) $("input[data-index='"+i+"']").trigger("click");
}
flag = true;
}
}else if(type == "uncheck"){
if (nowEnd !=null && lastEnd != null){
flag = false;
for(let i = parseInt(nowEnd)+1;i<=parseInt(lastEnd);i++){
if($("input[data-index='"+i+"']").is(":checked")) $("input[data-index='"+i+"']").trigger("click");
}
flag = true;
}
lastEnd = null;
}
}else if(mode == "batchUncheck"){
if(type == "uncheck"){
if (lastStart != null && lastEnd != null){
let agentNum = null; // 中间变量,支持向上/向下批量选择
if(lastStart > lastEnd){
agentNum = lastStart;
lastStart = lastEnd;
lastEnd = agentNum;
}
flag = false;
for(let i = parseInt(lastStart)+1;i<parseInt(lastEnd);i++){
if($("input[data-index='"+i+"']").is(":checked")) $("input[data-index='"+i+"']").trigger("click");
}
flag = true;
}
}
}
},250)
}
});
$(document).mouseup(function (e) {
if(!e.shiftKey){
// 还原
lastStart = null;
lastEnd = null;
nowEnd = null;
type = "";
mode = "";
flag = true;
}
})
}