Positioning Context Menu

后端 未结 3 1011
孤城傲影
孤城傲影 2021-02-20 02:15

I\'m trying to position a custom context menu with jQuery.
The first time it appears at the right position (mouse coordinates), but then the current position is being summed

3条回答
  •  死守一世寂寞
    2021-02-20 02:48

    The problem is that when you right click then left click elsewhere and then right click again, the position is incorrect.

    The root of the problem is that you set the offset before showing the element. It appears that it confuses jQuery if the element is set to display:none and then its offset is changed.

    To fix the problem you need to switch the show and the offset lines in your code:

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

    becomes

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

    Demo
    and
    Source

提交回复
热议问题