简体   繁体   English

事件touchstart在iPhone上不起作用

[英]Event touchstart doesn't work on iPhone

I have some code that generally works, except on iPhone. 除了在iPhone上,我有一些通常可以使用的代码。 When the window loads, this function is called. 加载窗口时,将调用此函数。 When I have the event as click , it works just fine on desktop, but not on mobile. 当我将事件设为click ,它在台式机上可以正常使用,但在移动设备上不能正常使用。 I've tried looking around for solutions for mobile, and touchstart seems to be the recommended solution. 我尝试过寻找移动解决方案,而touchstart似乎是推荐的解决方案。 But, though it works on emulators, it doesn't work on iPhone (tested on the latest OS version). 但是,尽管它可以在模拟器上运行,但不能在iPhone上运行(已在最新的OS版本上测试)。 Am I missing something? 我想念什么吗?

function addXClassOnClick() {
  var els = document.getElementsByClassName('item');

  Array.prototype.forEach.call(els, function(el) {
    el.addEventListener('touchstart', function() {
      el.parentElement.classList.toggle('x');
    }, false);
  });
}

Thanks in advance! 提前致谢!

Probably a duplicate of this SO question . 可能是这个SO问题的重复项。

If you're using an <a> tag, everything will work as expected on iPhones and other touch devices. 如果您使用的是<a>标签,那么一切将在iPhone和其他触摸设备上正常运行。 Otherwise, you should add CSS to whatever element with style cursor: pointer; 否则,您应该将CSS添加到具有样式cursor: pointer;任何元素cursor: pointer; .

Given the document fragment: 给定文档片段:

<div class="x">
    <div class="item">Item</div>
</div>

The anonymous event handler function's default scope is bound to the clicked element, and not to the clicked element's parent, which is the scope that classList.toggle should operate on. 匿名事件处理程序函数的默认范围绑定到clicked元素,而不绑定到clicked元素的父级,父级是classList.toggle应该在其上操作的范围。

(edit: According to the documentation, forEach passes undefined in as the scope of the callback function when not specified. The DOM element reference el has no scope to operate in. It's like the DOM is there, but the scope chain isn't.) (编辑:根据文档,未指定时, forEach传递时undefined为回调函数的范围。DOM元素引用el没有作用域。这就像DOM存在,但作用域链却没有。 )

To fix this, either call classList.toggle with the correct scope: 要解决此问题,请使用正确的范围调用classList.toggle

el.parentElement.classList.toggle.call(el.parentElement.classList, 'x');

or call forEach with the desired scope as a second argument: 或以所需的范围作为第二个参数调用forEach

Array.prototype.forEach.call(els, function(el) {
    // omit
}, els);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM