Set Div position to Mouse position with jQuery

前端 未结 3 860
南方客
南方客 2021-01-04 10:06

I am trying to position my Div wherever the user clicks on my Image.

test is my Div, and myimg is my image.

Here is my JS:<

相关标签:
3条回答
  • 2021-01-04 10:38

    It seems to work fine. I have set up a JSFiddle for you:

    http://jsfiddle.net/JPvya/

    Click on the image and the test div moves. The only change is using the $ short notation for JQuery instead of typing "JQuery" which, by the way is probably case sensetive and causing the problem!

    0 讨论(0)
  • 2021-01-04 10:47

    This works well enough for me, so your problem is likely elsewhere.

    HTML

    <img id="myimg" src="http://placekitten.com/200/300"/>
    <span id="test">This is a test</span>
    

    CSS

    #test {
        display: none;
        color: white;
    }
    

    JavaScript

    $(function() {
        $("#myimg").click(function(e) {
            var o = {
                left: e.pageX,
                top: e.pageY
            };
            $("#test").show(2000).offset(o);
        });
    });
    

    http://jsfiddle.net/mattball/haFMn/

    0 讨论(0)
  • 2021-01-04 10:59

    I think you probably want

    $("#test").css({position:"absolute", left:e.pageX,top:e.pageY});
    

    instead of

    $("#test").offset({left:e.pageX,top:e.pageY});
    
    0 讨论(0)
提交回复
热议问题