jQuery的mouseup事件在触摸设备上是否有效?

19

我在这里提问是因为找不到答案。目前我没有任何触摸设备,所以无法进行测试。

以下代码将隐藏容器外点击的所有子容器。

$(document).mouseup(function(e) {
  var container = $('#container');
  if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
  {
    $('.subcontainer').hide();
  }
});

这个功能在触摸设备上能用吗?或者有没有相当于 mouseup 的触摸设备事件?

2个回答

39
不,它不起作用。但这里有一个touchstarttouchend事件。
$(document).bind( "mouseup touchend", function(e){
  var container = $('#container');
  if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
  {
    $('.subcontainer').hide();
  }
});

谢谢!我应该绑定到$('body')还是$(document)? - Rafff
如果你的HTML有body标签,那么你可以同时做到两者。 - dknaack
2
@RafcioKowalsky 始终连接到其父元素。这将增强 DOM 搜索。 - Praveen
谢谢!因为#containerbody的子元素,所以将bind附加到body会更快 :) - Rafff
但是在IE、Edge和Safari上不支持触摸事件。 - Akin Hwan

0

为了让这个主题更新到最新(即2019年),请注意,jQuery在3.0版本中已经弃用了'bind'。

今天我在Android上首次测试“拇指滑块”(即输入元素,类型='range')时失败了,因为我的事件函数仅命名为mousemove和mouseup。

我只需将它们更改为:

$('#sliderID').on('touchmove mousemove', function(event){ ... } 和 $('#sliderID').on('touchend mouseup', function(event){ ... } 现在Web应用程序可以在PC(Windows-10)和Android(v7.1)上运行。我的jQuery版本是3.3.1。

(这是我可用于测试的唯一两个平台,但我相信这适用于所有主要浏览器。我在Chrome、Opera、Firefox和Edge-on-Win10上都成功了)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接