如何解决Javascript / HTML将图像添加到鼠标单击的中心位置
每当在屏幕上单击鼠标时,我都希望打印出一张图片。 这是我当前的Javascript和HTML代码。它只会打印h1,我不知道我在做什么错。
var image = document.getElementById("im"); // idenfitifes span eleme nt
var roll = false; // to kNow the image is moving or not,intitally it is not moving state hence value is false
image.addEventListener("mousedown",start,false); // at starting image is in rest
function mouse_move(x) // funciton to move image with mouse
{
var newX = x.clientX; // copies mouse x position
var newY = x.clientY; // copies mouse y position
image.style.left = newY + "px"; // assigns latest mouse position to span (image)
image.style.top = newX + "px";
}
function start(x) // span (image) starting no rolling mode
{
if(roll){ // when the mouse is moving
document.removeEventListener("mousemove",mouse_move); // initiages image span move
roll = !roll;
return;
}
roll = !roll; // when the mouse is not moving
document.addEventListener("mousemove",mouse_move,false);
}
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="utf-8" />
<title> Picture of Me! </title>
</head>
<body>
<h1> HTML File to move image along with mouse movement. </h1>
<script type="text/javascript" src="h5j.js">
<span id="im">
<img src="https://static01.nyt.com/images/2020/04/27/us/politics/00-trump-cand-page/00-trump-cand-page-mediumSquareAt3X.jpg" height="120" width="120"></img>
</span>
</body>
</html>
解决方法
您可以像这样使用AddEventListener函数
document.addEventListener("mousedown",mouse_move,false);
addEventListener的语法为: addEventListener(“事件名称”,“您的函数名称,要在事件发生后运行的函数”)
当您需要在click事件中运行时,只需将事件名称从“ mousedown”更改为“ click”,例如: document.addEventListener(“ click”,mouse_move,false);
您必须使用“ click”事件而不是“ mousedown”事件
喜欢:
document.addEventListener("click",false);
<code>
var image = document.getElementById("im");
var roll = false;
image.addEventListener("click",start,false);
function mouse_move(x)
{
var newX = x.clientX; // copies mouse x position
var newY = x.clientY; // copies mouse y position
image.style.left = newX + "px";
image.style.top = newY+ "px";
}
function start(x) // span (image) starting no rolling mode
{
if (roll) { // when the mouse is moving
document.removeEventListener("click",mouse_move); // initiages image span move
roll = !roll;
return;
}
roll = !roll; // when the mouse is not moving
}
document.addEventListener("click",false);
</code>
,
似乎您在DOM
完成加载之前试图通过id获取图像元素。
我建议以下其中之一:
- 将
<script>
标记移至</body>
和</html>
之间的页面底部 - 将
defer
添加到<script>
标记中,这将导致脚本在DOM之后加载。 - 将JavaScript的第一块移动到
DOMContentLoaded
事件监听器中,如下所示。
var roll = false;
var image;
document.addEventListener('DOMContentLoaded',function(){
image = document.getElementById("im");
image.addEventListener("mousedown",false);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。