定位上下文菜单

use*_*330 9 javascript jquery contextmenu

我正在尝试使用jQuery定位自定义上下文菜单.
它第一次出现在正确的位置(鼠标坐标),但随后当前位置与新位置相加,以便菜单从屏幕上消失.
这是JavaScript:

<script>
$(function(){
    $('#box').hide();

    $(document).bind("contextmenu", function(e) {
        $("#box").offset({left:e.pageX, top:e.pageY});
        $('#box').show();
        e.preventDefault();
    });

    $(document).bind("click", function(e) {
        $('#box').hide();
    });
    $('#box').bind("click", function(e) {
        $('#box').hide();
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 9

不要使用offset方法,css而是尝试,绝对定位上下文菜单:

$("#box").css({left:e.pageX, top:e.pageY});
Run Code Online (Sandbox Code Playgroud)

CSS:

#box {
    ...
    position: absolute;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/smxLk/


Aks*_*kar 7

试用位置:固定;根据以下条件更改上下文菜单的位置 -

var windowHeight = $(window).height()/2;
var windowWidth = $(window).width()/2;
if(e.clientY > windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY > windowHeight && e.clientX > windowWidth) {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("top", "auto");
} else if(e.clientY <= windowHeight && e.clientX <= windowWidth) {
  $("#contextMenuContainer").css("left", e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("right", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
} else {
  $("#contextMenuContainer").css("right", $(window).width()-e.clientX);
  $("#contextMenuContainer").css("top", e.clientY);
  $("#contextMenuContainer").css("left", "auto");
  $("#contextMenuContainer").css("bottom", "auto");
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/AkshayBandivadekar/zakn7​​Lwb/14/

  • 这就是我要找的!谢谢 (2认同)

Jos*_*kle 5

问题是,当您右键单击然后在其他位置单击鼠标左键然后再次右键单击时,位置不正确。

问题的根源是您在显示元素之前设置了偏移量。如果将元素设置为display:none,然后更改其偏移量,似乎会使jQuery感到困惑。

要解决此问题,您需要在代码中切换showoffset行:

$(document).bind("contextmenu", function(e) {
    $("#box").offset({left:e.pageX, top:e.pageY});
    $('#box').show();
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

变成

$(document).bind("contextmenu", function(e) {
    $('#box').show();
    $("#box").offset({left:e.pageX, top:e.pageY});
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

演示

来源