使用鼠标事件使用Javascript移动图像 [英] Move an image with Javascript using mouse events

查看:39
本文介绍了使用鼠标事件使用Javascript移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该足够简单,但是每次尝试时,我都会遇到一个不同的问题.

This should be simple enough, but every time I try I end up with a different issue.

我正在尝试使用鼠标事件(例如mousedown,mouseup,mousemove,clientX和clientY)在屏幕上移动图像.然后,我尝试使用绝对定位将其应用于图像.

I am trying to move an image around the screen using mouse events such as mousedown, mouseup, mousemove, clientX and clientY. I am then trying to apply it to the image using absolute positioning.

我以为下面的代码可以在我第一次单击时获得坐标,然后通过鼠标移动来更新它们,但这是行不通的.

I thought the below code would work as I get the coordinates on the initial click, and then the idea was to update them with mouse movement, but this does not work.

var image;
var dog = document.getElementById("dogPic");
var cat = document.getElementById("catPic");

dog.addEventListener("mousedown", initialClick, false);
cat.addEventListener("mousedown", initialClick, false);




function initialClick(e) {
    var initialX = e.clientX;
    var initialY = e.clientY;
    image = document.getElementById(this.id);

    document.addEventListener("mousemove", function(e){

        var newX = e.clientX - initialX;
        var newY = e.clientY - initialY;  


        image.style.left = newX;
        image.style.top = newY;
    }, false);

}

我并没有要求完整的答案,但是有人可以指导我如何使用鼠标移动事件在屏幕上拖动图像吗?

I am not asking for a complete answer, but can anyone direct me as to how I can approach dragging an image around the screen using the mouse movement events?

谢谢

推荐答案

var dog = document.getElementById("dogPic");
var cat = document.getElementById("catPic");
var moving = false;

dog.addEventListener("mousedown", initialClick, false);
cat.addEventListener("mousedown", initialClick, false);


function move(e){

  var newX = e.clientX - 10;
  var newY = e.clientY - 10;

  image.style.left = newX + "px";
  image.style.top = newY + "px";

  
}

function initialClick(e) {

  if(moving){
    document.removeEventListener("mousemove", move);
    moving = !moving;
    return;
  }
  
  moving = !moving;
  image = this;

  document.addEventListener("mousemove", move, false);

}

#dogPic, #catPic {
  width: 20px;
  height: 20px;
  position: absolute;
  background: red;
  top: 10px;
  left: 10px;
}

#dogPic {
  background: blue;
  top: 50px;
  left: 50px;
}

<div id="dogPic"></div>
<div id="catPic"></div>

这篇关于使用鼠标事件使用Javascript移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆