<select multiple> 无需滚动,无需按住 ctrl 单击即可在移动设备上工作

<select multiple> with no scrolling and no ctrl click required and work on mobile

我的问题与此处描述的问题和 'answered' 非常相似:

我希望能够在不需要 CTRL 且不向上滚动的情况下单击多个元素,但似乎 Chrome Mobile (android) 仍然可以看到鼠标按下(尽管不涉及鼠标),然后由于 preventDefaults 而不会出现选项,例如:

修复它的最佳方法是什么?

如果有帮助,这里是 jsfiddle:https://jsfiddle.net/95ntdrjc/

没有JQuery请。

const selectElem = document.querySelector('select');
selectElem.onmousedown = function(e) {
  e.preventDefault();
  const st = this.scrollTop;
  e.target.selected = !e.target.selected;
  setTimeout(() => this.scrollTop = st, 0);
  this.focus();
};

selectElem.onmousemove = function(e) {
  e.preventDefault();
};
<select multiple>
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

通过非常简单的修复解决了!

selectElem.ontouchstart = function() {selectElem.onmousedown = null;};

在 touchStart 上,将触发这些事件:

  • 触摸启动
  • 零个或多个触摸移动事件,具体取决于手指的移动
  • 触摸端
  • 鼠标移动
  • 鼠标按下
  • 鼠标弹起
  • 点击

https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent#Event_order

这会取消 mousedown 过程中发生的事情,因此移动设备可以正常继续,而桌面版本不滚动并且不需要 CTRL 到 select 多个。