js 通用拖拽多选工具函数

ts 代码

复制下面的代码到浏览器控制台执行,按住 ctrl 即可查看拖拽选中所有 td 元素的效果,修改其中的选择器即可实现拖拽选中任意想要可选中的元素

"use strict";
function 拖拽多选() {
  let flag = false;
  let 选区 = [0, 0, 0, 0];
  const div = document.createElement("div");
  div.style.cssText = `position: fixed;background: gray;opacity: .3;`;
  document.body.appendChild(div);
  let 选区矩形 = 选区_to_矩形(选区);
  document.addEventListener("mousedown", (event) => {
    console.log("mousedown", event);
    遮罩.remove();
    if (event.ctrlKey) {
      flag = true;
      选区[0] = event.clientX;
      选区[1] = event.clientY;
      event.preventDefault(); // 阻止默认行为
      event.stopPropagation(); // 阻止事件冒泡
    }
  });
  document.addEventListener("mousemove", (event) => {
    if (!flag) {
      return;
    }
    选区[2] = event.clientX;
    选区[3] = event.clientY;
    选区矩形 = 选区_to_矩形(选区);
    div.style.left = 选区矩形[0] + "px";
    div.style.top = 选区矩形[1] + "px";
    div.style.width = 选区矩形[2] - 选区矩形[0] + "px";
    div.style.height = 选区矩形[3] - 选区矩形[1] + "px";
  });
  document.addEventListener("mouseup", (event) => {
    if (!flag) {
      return;
    }
    const td_list = Array.from(document.querySelectorAll("td"));
    const 选中 = td_list.filter((el) => 矩形相交(选区矩形, HtmlElement_to_矩形(el)));
    console.log(选区矩形, 选中.map(HtmlElement_to_矩形), 选中);
    选中.map(HtmlElement_to_矩形).forEach(遮罩.add);
    flag = false;
  });
}
拖拽多选();
function HtmlElement_to_矩形(el) {
  const rect = el.getBoundingClientRect();
  return [rect.left, rect.top, rect.right, rect.bottom];
}
function 矩形相交(rect1, rect2) {
  var a_min_x = rect1[0];
  var a_min_y = rect1[1];
  var a_max_x = rect1[2];
  var a_max_y = rect1[3];
  var b_min_x = rect2[0];
  var b_min_y = rect2[1];
  var b_max_x = rect2[2];
  var b_max_y = rect2[3];
  return a_min_x <= b_max_x && a_max_x >= b_min_x && a_min_y <= b_max_y && a_max_y >= b_min_y;
}
function 选区_to_矩形(选区) {
  if (选区[0] > 选区[2] || 选区[1] > 选区[3]) {
    return [选区[2], 选区[3], 选区[0], 选区[1]];
  } else {
    return 选区;
  }
}
var 遮罩;
(function (遮罩) {
  let list = [];
  function add(rect) {
    const div = document.createElement("div");
    div.style.cssText = `position: fixed;background: gray;opacity: .3;`;
    div.style.left = rect[0] + "px";
    div.style.top = rect[1] + "px";
    div.style.width = rect[2] - rect[0] + "px";
    div.style.height = rect[3] - rect[1] + "px";
    list.push(div);
    document.body.appendChild(div);
  }
  遮罩.add = add;
  function remove() {
    list.forEach((el) => el.remove());
    list = [];
  }
  遮罩.remove = remove;
})(遮罩 || (遮罩 = {}));

拖拽多选效果
如果是在 shenzilong.cn 站点查看本文章,可以按住 ctrl 在下面的表格尝试效果
|拖拽|多选|测试|

|--|--|--|

|1|2|7|

|3|4|8|

|5|6|9|

原文地址

你可能感兴趣的:(javascript,拖拽)