[英]How can I place an image with the onclick() function from JS
So I think I know how to do it. 所以我想我知道该怎么做。 I need to get the coordinates of the cursor when the onclick()
function is called. 调用onclick()
函数时,我需要获取光标的坐标。 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 编辑:我更改了代码以将图像创建为DOM对象
Based on @AyoubLaazazi 's answer, try this: 基于@AyoubLaazazi的答案,请尝试以下操作:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.