How to position a popup div based on the position of where the cursor clicks

前端 未结 2 600
梦谈多话
梦谈多话 2021-02-15 03:07

I am trying to position a popup div below:

Hi
相关标签:
2条回答
  • 2021-02-15 03:44

    Try adding position: absolute to your div. Make sure it isn't located within another div that has relative positioning.

    <div style="position: absolute; display:none;height:200px;width:200px;border:3px solid green;" id="popup">Hi</div>
    

    Top and left only work for elements with relative, absolute or fixed positioning.

    0 讨论(0)
  • 2021-02-15 03:52

    The problem lie in the fact that offset() do not return the correct mouse position, try event.pageX and event.pageY instead:

    $(document).ready(function(){
        $('div#d').bind('click', function (event) {
        $('#popup').css('left',event.pageX);      // <<< use pageX and pageY
        $('#popup').css('top',event.pageY);
        $('#popup').css('display','inline');     
        $("#popup").css("position", "absolute");  // <<< also make it absolute!
        });
    });
    

    See here.

    0 讨论(0)
提交回复
热议问题