javascript - 禁用智能手机上的长按

标签 javascript html long-press

我已经有一个可用的代码来禁用长按 但现在我不想通过 ID 获取元素。我不可能为每个特定项目添加 Id。 我想让它适用于名称标签中的每个图片。 但是,现在不起作用。请帮忙。

原工作线: PreventLongPressMenu(document.getElementById('theimage'));

编辑行: PreventLongPressMenu(document.getElementByTagName('body img'));

整个代码:

<!DOCTYPE html>
<html>
<head>
  <script>
    function absorbEvent_(event) {
      var e = event || window.event;
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }

    function preventLongPressMenu(node) {
      node.ontouchstart = absorbEvent_;
      node.ontouchmove = absorbEvent_;
      node.ontouchend = absorbEvent_;
      node.ontouchcancel = absorbEvent_;
    }

    function init() {
      preventLongPressMenu(document.getElementByTagName('body img'));
    }
  </script>
  <style>
    *:not(input):not(textarea) {
    -webkit-user-select: none; /* disable selection/Copy of UIWebView */
        -webkit-touch-callout: none; /* disable the IOS popup when long-press on a link */

    }
  </style>
</head>
<body onload="init()" id="theimage" >
  <img src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>

最佳答案

您拼写错误了方法名称,并且没有传递正确的字符串。它是 getElementsByTagName (注意元素上的 s),您只需传递标签的名称而不是 css 选择器。您还必须修改函数以循环结果,因为它将是一个节点列表

preventLongPressMenu(document.getElementsByTagName('img'));

function preventLongPressMenu(nodes) {
  for(var i=0; i<nodes.length; i++){
     nodes[i].ontouchstart = absorbEvent_;
     nodes[i].ontouchmove = absorbEvent_;
     nodes[i].ontouchend = absorbEvent_;
     nodes[i].ontouchcancel = absorbEvent_;
  }
}

如果手机浏览器支持,也可以使用querySelector/querySelectorAll ,它允许您使用 css 选择器来选择元素

preventLongPressMenu(document.querySelectorAll('body img'));

function preventLongPressMenu(nodes) {
  for(var i=0; i<nodes.length; i++){
     nodes[i].ontouchstart = absorbEvent_;
     nodes[i].ontouchmove = absorbEvent_;
     nodes[i].ontouchend = absorbEvent_;
     nodes[i].ontouchcancel = absorbEvent_;
  }
}

关于javascript - 禁用智能手机上的长按,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969383/

相关文章:

android - 长按 surfaceView ( android )

Android长按滚动

javascript - 在 javascript 中使用变量重复

html - CSS 不能在不同的机器上工作

html - 标题、导航中的边距为 0

javascript - 放映幻灯片动画时div的宽度变小

android - 列表项长按转场

javascript - 如何通过javascript访问XUL覆盖中的元素?

javascript - 迭代数组并仅删除 id

javascript - 隐藏或禁用 DevExtreme Scheduler 中的编辑属性以及其他问题?