提问者:小点点

Chrome上不触发的可拖动切换复选框事件(JS/CSS)


我试图尽可能地复制iOS的滑动切换,只使用JS和CSS。 我在这里找到了一支由@3RROR404提供的出色的钢笔,它正好做到了这一点。

虽然它在iOS Safari中运行良好,但在Chrome(桌面和Android)中,它只对点击做出反应,而不对拖动做出反应,我不明白这是为什么。 我甚至添加了mouseup/mousedown/mousemove事件,但仍然是不允许的。

for (let i = 0; i < switches.length; i++) {

  const switchEl = switches[i];

  switchEl.draggable = true;

  ['dragstart', 'touchstart','mousedown'].forEach(function(e) {
    switchEl.addEventListener(e, onDragStart);
  });

  ['dragover', 'touchmove','mousemove'].forEach(function(e) {
    switchEl.addEventListener(e, onDragOver);
  });

  ['dragend', 'touchend','mouseup'].forEach(function(e) {
    switchEl.addEventListener(e, onDragEnd);
  });

}

请在此处查看我编辑的钢笔:https://codepen.io/azerty1234/pen/bajlqgn

你知道为什么会发生这种情况或者可能的解决办法吗? 谢啦!


共1个答案

匿名用户

我在钢笔里发现了一个窃听器。

它为dragstart添加了相同的事件处理程序,而touchstartChrome(在移动模式下)使用了touchstart事件。

TouchStart事件没有PageXPagey变量(第64和65行)

它具有evt.touches[0].pageXevt.touches[0].pagey

您应该检查evt.type是否等于“dragstart”:

function onDragStart(evt) {
  evt = evt || window.event;
  const x = (evt.type == 'touchstart') ? evt.touches[0].pageX : evt.pageX,
        y = (evt.type == 'touchstart') ? evt.touches[0].pageY : evt.pageY;
...

function onDragOver(evt) {
  evt = evt || window.event;

  evt.preventDefault();
  const x = (evt.type == 'touchmove') ? evt.touches[0].pageX : evt.pageX,
        y = (evt.type == 'touchmove') ? evt.touches[0].pageY : evt.pageY;
...

ondragover(64,65)和ondragstart(90,91)中应用此更改,它将在移动模式下工作