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'sposition
toabsolute
and set the position usingleft
andtop
. – PeeHaa Commented Mar 14, 2012 at 14:42
2 Answers
Reset to default 3Make 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;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745352556a4623922.html
评论列表(0条)