【发布时间】:2014-10-15 08:53:01
【问题描述】:
我正在做一个上下文菜单,我对此有一些问题/疑问。 这是代码:
HTML:http://jsfiddle.net/Ls9p0ht6/1/
<body oncontextmenu="return false" onclick="hide()">
<div style="display:none;" id="menu">
<table border="1" width="100px">
<tr>
<td>
<div class="item">
<a href="http://www.google.es">TEST 1</a>
</div>
</td>
</tr>
<tr>
<td>
<div class="item">TEST 2</div>
</td>
</tr>
</table>
</div>
<script language="javascript" type="text/javascript">
function show(e) {
var posx = e.clientX +window.pageXOffset +'px';
var posy = e.clientY + window.pageYOffset + 'px';
document.getElementById('menu').style.position = 'absolute';
document.getElementById('menu').style.display = 'inline';
document.getElementById('menu').style.left = posx;
document.getElementById('menu').style.top = posy;
}
function hide() {
document.getElementById('menu').style.display = 'none';
}
</script>
<div oncontextmenu="show(event);"class="menu-item" id="option1">
option 1
</div>
<div oncontextmenu="show(event);"class="menu-item" id="option2">
option 2
</div>
</body>
它工作正常,当我右键单击时,我的上下文菜单会出现,但是(如您所见)当我单击任何位置(正文事件)时,它必须被隐藏,但它不起作用......只有在我点击一个“菜单项”类。
另一个问题是: 是否可以通过 oncontextmenu 事件获取元素 ID?我的意思是,例如,我右键单击“选项 1”,我想查看上下文菜单和带有元素 ID 的警报。可以在同一个活动上做吗?
【问题讨论】:
-
在您的 html 标记中包含内联 javascript 通常是不好的做法。创建一个单独的文件,然后执行:
var body = document.getElementsByTagName("body")[0]; body.addEventListener("contextmenu", function(e) { e.preventDefault() }); -
我是新手……你是说这个吗? jsfiddle.net/Ls9p0ht6/6 但你的 var 正文不起作用
-
我已经回答了您的问题,但您误认为 var 正文不起作用。 jsFiddle 使用 iframe,而您的真实文档的正文非常短。使用我的答案,但是在 jsfiddle 中尝试时,请尝试在菜单旁边右键单击。
-
是的:D 它解决了 jsFiddle。谢谢。 “e.preventDefault()”是关键吗?这意味着我的上下文菜单将具有默认值 (display:none) no?
标签: javascript html contextmenu