So I think I know how to do it. I need to get the coordinates of the cursor when the onclick()
function is called. The thing is, I'm not sure how I can create a new image when I click. I'm sorry for not showing my attempts. They exist, but basically do nothing. Does anyone know how to do this? Thanks.
edit: Note that the images can't be there to begin with. They have to be created on click.
使用CSS设置默认值以隐藏image属性,并使用click函数更改CSS以显示而不是隐藏。
<body style="position: relative">
<script>
var img = null;
function placeImage(e) {
if(img == null){
img = document.createElement("IMG");
img.setAttribute("src", "img.png");
img.setAttribute("width", "40");
img.setAttribute("height", "40");
img.style.position = "absolute";
document.body.appendChild(img);
}
img.style.left = (e.clientX - (img.width / 2)) + "px";
img.style.top = (e.clientY - (img.height / 2)) + "px";
}
document.addEventListener("click", placeImage);
</script>
</body>
This will place the center of the image in the point where you click.
EDIT: I changed the code to create an image as a DOM Object
Based on @AyoubLaazazi 's answer, try this:
img = document.getElementById("img") counter = 0 function placeImage(e) { imgc = $("#img").clone().appendTo("body")[0] imgc.style.visibility = "visible" imgc.style.left = (e.clientX - (img.width / 2)) + "px"; imgc.style.top = (e.clientY - (img.height / 2)) + "px"; counter++ } document.addEventListener("click", placeImage)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <img src="https://d21ii91i3y6o6h.cloudfront.net/gallery_images/from_proof/8007/large/1441565237/stack-overflow-logo.png" style="visibility: hidden; position: absolute" id="img"/> </body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.