最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery - add image at specific co-ordinates - Stack Overflow

programmeradmin1浏览0评论

Is it possible to add a image at a clicked position within a div using jquery?

I need to develop a small game basically involves clicking the screen to guess a position - a image is placed wherever the user clicks...

I know how to get the X & Y coordinates of the place that was clicked - but have no idea how to place an image in that position...

Any help would be great-fully received!

Cheers Paul

Is it possible to add a image at a clicked position within a div using jquery?

I need to develop a small game basically involves clicking the screen to guess a position - a image is placed wherever the user clicks...

I know how to get the X & Y coordinates of the place that was clicked - but have no idea how to place an image in that position...

Any help would be great-fully received!

Cheers Paul

Share Improve this question asked Mar 14, 2012 at 14:39 DancerDancer 17.8k40 gold badges131 silver badges213 bronze badges 1
  • 3 Simply add the new image right below the <body in the DOM and set it's position to absolute and set the position using left and top. – PeeHaa Commented Mar 14, 2012 at 14:42
Add a ment  | 

2 Answers 2

Reset to default 3

Make sure the div is set to position: relative then when you create your image make it position:absolute and set the top and left properties to your click coordinates. Something like this:

$('#yourdiv').append( 
  '<img src="/path/to/your/image.jpg" 
     style="width:auto;height:auto;position:absolute;
            left:' + yourxcoord + ';top:'+ yourycoord +'" />");

You can check a simple example from here http://jsfiddle/qA2jV/

jquery:

$(document).click(function(e){
    $(".foo").remove()
    $("body").append("<span class='foo'/>")
    $(".foo").css("left",e.pageX)
    $(".foo").css("top",e.pageY)
})

css:

.foo{
    background-image:url("https://s-static.ak.facebook./rsrc.php/v1/ym/r/9vuAQCVid3f.png");
    background-repeat:no-repeat;
    display:inline-block;
    position:absolute;
    height:16px;
    width:16px;
}
发布评论

评论列表(0)

  1. 暂无评论