[英]How to perform some action when a user touches anywhere that isn't a link/anchor etc?
I'm using html/javascript with iOS and UIWebView. 我在iOS和UIWebView中使用html / javascript。 I want to invoke an objective-c method when the user touch anywhere on the page that isn't a link. 当用户触摸页面上不是链接的任何地方时,我想调用Objective-C方法。
At the moment I have 此刻我有
...
<BODY ontouchend="bodyTouch();">
<HEAD>
<script language="javascript" type="text/javascript">
function bodyTouch() {
invokeObjectiveC();
}
}
</script>
...
<DIV id=buttons>
<A id=navigator href="CustomScheme:SomeAction"></A>
....
How can I set things up so that bodyTouch() only gets invoked if the user touches anywhere on the screen that isn't a link/button/anchor etc. 如何设置内容,以便仅当用户触摸屏幕上不是链接/按钮/锚等的任何位置时,bodyTouch()才会被调用。
==== Update === ====更新===
Thanks for lots of answers folks. 谢谢大家的回答。 Unfortunatly I couldn't get any of them to work (now my InvokeObjectiveC() doesn't get called at all when I try any of them). 不幸的是,我无法让它们中的任何一个起作用(现在,当我尝试其中的任何一个时,我的InvokeObjectiveC()都不会被调用)。 I'm an iOS developer and don't know html/javascript. 我是iOS开发人员,不了解html / javascript。 I'll do a bit of studying as I don't understand any of the answers at the moment with my limited knowledge, then try them once I understand what they are doing and try to figure out why its not working. 我将做一些研究,因为我目前有限的知识还不了解任何答案,然后在了解他们的工作后尝试它们,并弄清楚为什么它不起作用。 I'll mark one of the answers as accepted in due course. 我会在适当时候将其中一个答案标记为接受。 Cheers 干杯
document.body.addEventListener('click', function(event){
bodyClick();
}, false);
document.querySelector('a').addEventListener('click', function(event){
event.stopPropagation();
}, false);
Learn more about stopPropagation
at Mozilla Developer Network 在Mozilla开发人员网络上了解有关stopPropagation
更多信息
give this one a shot, you should be able to place this anywhere in the document 试一试,您应该可以将其放在文档中的任何位置
<script>
document.addEventListener('DOMContentLoaded', function () {
document.documentElement.addEventListener('click', function (e) {
/* CHECK IF THE TARGET IS IN YOUR BANLIST */
if (['A', 'BUTTON'].indexOf(e.target.tagName) === -1) {
/* I WOULD CALL THESE FOR GOOD MEASURE */
e.preventDefault();
e.stopPropagation();
/* THIS IS YOUR FUNCTION */
invokeObjectiveC();
}
}, true);
}, false);
</script>
this does not work on the input[type=button] looking buttons, if you need that as well let me know 这在输入[type = button]外观按钮上不起作用,如果您也需要的话,请告诉我
使用jQuery委托和选择器,但请注意,如果原始元素触发该事件使用stopPropagation
Similar to Roderick's response, but a bit more cross-browser friendly 与Roderick的回应类似,但对跨浏览器更友好
document.getElementsByTagName('html')[0].addEventListener('click', function (ev) {
var el, elN;
ev = ev || window.event;
el = ev.target || ev.srcElement;
elN = el.nodeName.toLowerCase();
if (elN == 'a' || elN == 'input') return false;
invokeObjectiveC();
}, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.