我已经有了一个可用的代码来禁用长按压,但是现在我不想按ID获取元素,我不可能为每个特定的项目添加Id。我想让它适用于名字标签中的每个img。但是,它现在不起作用了。请帮帮忙。
原工作线: 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>发布于 2014-07-26 09:20:34
您正在拼写方法名,而不是传递正确的字符串。它是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_;
}
}发布于 2016-12-30 00:16:19
您还可以通过JQuery分配事件处理程序,而无需对每个节点使用for:
function preventLongPressMenu(node) {
node.on('touchstart', absorbEvent_);
node.on('touchmove', absorbEvent_);
node.on('touchend', absorbEvent_);
node.on('touchcancel', absorbEvent_);
}所以,而不是这个:
function init() {
preventLongPressMenu(document.getElementByTagName('body img'));
}这样做:
function init() {
preventLongPressMenu($('body img'));
}仅仅为了使用JQuery,就必须实现它:
来自Google的:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>或Microsoft:“我更喜欢谷歌!:)"
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>更好的做法是从两个CDN中的一个下载该文件,并将其作为本地文件,这样您的网站的启动加载速度就会更快!
是你的选择!
在我看来,它比使用DOM简单得多,我喜欢JQuery!:)
https://stackoverflow.com/questions/24969383
复制相似问题