简体   繁体   English

右键单击显示DIV

[英]Display DIV on right click of image

I'm trying to figure out how I can get a DIV to show at the position of the mouse when someone right clicks on an image. 我试图弄清楚当有人右键单击图像时如何使DIV显示在鼠标的位置。 An example can be found here . 这里可以找到一个例子。

I've searched around and found the following code... 我到处搜索并找到以下代码...

$('img').bind('contextmenu', function(e){
return false;
});

This of course will prevent the right click. 这当然会阻止右键单击。 Though I don't know how to make the DIV appear at the location of the mouse click. 虽然我不知道如何使DIV出现在鼠标单击的位置。

May I please get pointed in the right direction? 我能指出正确的方向吗?

Thanks! 谢谢!

I've thrown together a quick demo ( check it out here ) of how to possibly do this. 我已经汇总了一个如何进行此操作的快速演示( 在此处查看 )。 The div is absolutely positioned and we capture the contextmenu event, on which we preventDefault() and set the position of the div based on the pageX and pageY key's in the event object. 绝对定位div并捕获contextmenu事件,在该事件上我们防止pageX preventDefault()并根据event对象中的pageXpageY键设置div的位置。

The JS looks something like this: JS看起来像这样:

$('body').on('contextmenu', function(event) {
    event.preventDefault();
    $('div').css({
        'top': event.pageY,
        'left': event.pageX
    });
});​

And the CSS looks something like this: CSS看起来像这样:

body {
    width: 500px;
    height: 500px;
}

div {
    width: 100px;
    height: 100px;    
    background-color: #ccc;
    position: absolute;
    top: 0;
    left: 0;
}​

I've tested the demo in the latest Firefox and Chrome, as well as IE7 - IE9, and it has worked in all of them. 我已经在最新的Firefox和Chrome以及IE7-IE9中测试了该演示,并且已在所有这些工具中使用。 Hope this helps. 希望这可以帮助。

You can use the offsetX and offsetY properties of the event object that gets passed to the contextmenu handler like so: 您可以使用传递给contextmenu处理程序的事件对象的offsetXoffsetY属性,如下所示:

HTML: HTML:

<img src="http://mikecane.files.wordpress.com/2007/03/kitten.jpg" alt="click me, I'm a kitten!" id="picture" />

<div id="pictureCaption">Pretty picture of a kitten</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Javascript: 使用Javascript:

​$('#pictureCaption').hide();

$('#picture').contextmenu( function(e) {
    e.preventDefault();
    $('#pictureCaption').offset( {top: e.offsetY, left:e.offsetX} ).show();
})​​​​​​​​​​​​​​​;​​​​

jsFiddle here: http://jsfiddle.net/HFC5g/ jsFiddle在这里: http : //jsfiddle.net/HFC5g/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM