Firefox 在文本选择过程中不发出鼠标事件?

Firefox does not emit mouse events during text selection?

提问人:インキャ 提问时间:10/4/2023 更新时间:10/4/2023 访问量:19

问:

我有一个数据网格组件,它支持类似于 excel/google 表格的任意单元格范围选择。我通过鼠标按下来确定起始单元格,通过记录获得mouseenter的最后一个单元格来确定结束节点(不是mouseup,因为用户可以在网格之外使用鼠标up)。我目前正在添加一项增强功能,以便当用户将选择拖动到网格的当前视口之外时,它将自动水平和垂直滚动。我的想法是利用本机文本选择,因为当您选择文本时,浏览器默认会滚动容器。但后来我发现它适用于 Chrome,但不适用于 Firefox。

下面是一个简化的示例:https://jsfiddle.net/n6gm5ekr/43/。在Chrome和Firefox中运行它,应该很容易发现差异。

body {
  padding: 20px;
}

.mouseTarget {
  box-sizing: border-box;
  width: 70px;
  border: 2px solid grey;
  display: inline-block;
  cursor: default;
  padding: 2px;
  margin: 2px;
  box-sizing: border-box;
  overflow: hidden;
  /* user-select: none; */
}

.mouseTarget span::selection {
  color: black;
  background-color: yellow;
}

.table {
  width: 500px;
  height: 200px;
  overflow: auto;
  border: 2px solid blue;
}
const numRows = 130;
const numCols = 10;

const table = document.createElement('div');
table.classList.add('table');

for (let i = 0; i < numRows; i++) {
    const row = document.createElement('div');
  
  for (let j = 0; j < numCols; j++) {
    const cell = document.createElement('div');
    const span = document.createElement('span');
    cell.append(span);
    span.textContent = `Cell ${i}-${j}`;
    cell.classList.add("mouseTarget");
    cell.draggable=false;
    row.append(cell);
    row.style.width = `${numCols * 74}px`;
  }
  
  table.append(row);
}

document.body.append(table);

let downEventCount = 0;
let upEventCount = 0;
let enterEventCount = 0;
let leaveEventCount = 0;
const mouseTargets = document.querySelectorAll(".mouseTarget");

for (let mouseTarget of mouseTargets) {
  mouseTarget.addEventListener("mouseenter", (e) => {
    mouseTarget.style.border = "2px dotted orange";
    mouseTarget.style.backgroundColor = "orange";
    mouseTarget.classList.add('hover');
    enterEventCount++;
    console.log(`This is mouseenter event ${enterEventCount}.`);
  });
  mouseTarget.addEventListener("mouseleave", (e) => {
    mouseTarget.style.border = "2px solid grey";
    mouseTarget.style.backgroundColor = "transparent";
    mouseTarget.classList.add('hover');
    leaveEventCount++;
    console.log(`This is mouseleave event ${leaveEventCount}.`);
  });
  mouseTarget.addEventListener("mousedown", (e) => {
    mouseTarget.style.border = "2px solid red";
    downEventCount++;
    console.log(`This is mousedown event ${downEventCount}.`);
  });
    mouseTarget.addEventListener("mouseup", (e) => {
    mouseTarget.style.border = "2px solid green";
    upEventCount++;
    console.log(`This is mouseup event ${upEventCount}.`);
  });
}

我找不到官方文档来确认这种行为是设计使然,当我在多个 div 中拖动选择时,Firefox 不会发出任何 mouseenter/mouseleave/mouseover/mousemove/etc. 事件。

寻找解决方法的建议,以及指向 Chrome 和 Firefox 之间行为差异背后的基本原理的指针。

谢谢!

javascript firefox 事件鼠标 输入 文本选择

评论


答: 暂无答案