Detectinig the target of the click using JavaScript?

纵然是瞬间 提交于 2019-12-12 17:24:30

问题


How do I detect what object or ID or the user right-clicked on? I'm using the onContextMenu to trigger a function but I don't know how to detect the target.


回答1:


<html>
<head>
<script type="text/javascript">
    if (document.addEventListener) {
        document.addEventListener('contextmenu', function(e) {
            alert(e.target.nodeName); //or e.target.getAttribute('id') 
            e.preventDefault();
        }, false);
    } else {
        document.attachEvent('oncontextmenu', function(e) {
            alert(window.event.srcElement.nodeName); //or e.srcElement and then like above
            window.event.returnValue = false;
        });
    }
</script>
</head>
<body>
<span>Lorem ipsum...</span><br/>
body content
</body>
</html>

PS. I've seen similar code before ;)




回答2:


Your handler should accept an event object as its parameter; the srcElement property of the event will be the object that triggered the event.




回答3:


As Patrick mentioned, you are receiving an event object as parameter to your onContentMenu callback function, where you can find the element triggered the event. I am using this code for cross-browser compatibility.

var oE = event.srcElement || event.originalTarget;

Note: originalTarget is Mozilla specific. You might want to pay attention to event.target https://developer.mozilla.org/en/DOM/event.target



来源:https://stackoverflow.com/questions/4909517/detectinig-the-target-of-the-click-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!