最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Move an image with Javascript using mouse events - Stack Overflow

programmeradmin3浏览0评论

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

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?

Thanks

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

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?

Thanks

Share Improve this question asked Nov 26, 2015 at 23:37 bcBornbcBorn 1321 gold badge1 silver badge8 bronze badges 1
  • 2 do #dogPic and #catPic have style position: absolute;? – Sergio Commented Nov 26, 2015 at 23:45
Add a comment  | 

5 Answers 5

Reset to default 9

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>

I made a modification to have a more realistic dragging experience. This required adding an X and Y offset so instead of jumping when picked up, the object seems to just move as expected.

let gMouseDownX = 0;
let gMouseDownY = 0;
let gMouseDownOffsetX = 0;
let gMouseDownOffsetY = 0;

function addListeners() {
    document.getElementById('cursorImage').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
    gMouseDownX = e.clientX;
    gMouseDownY = e.clientY;

    var div = document.getElementById('cursorImage');

    //The following block gets the X offset (the difference between where it starts and where it was clicked)
    let leftPart = "";
    if(!div.style.left)
        leftPart+="0px";    //In case this was not defined as 0px explicitly.
    else
        leftPart = div.style.left;
    let leftPos = leftPart.indexOf("px");
    let leftNumString = leftPart.slice(0, leftPos); // Get the X value of the object.
    gMouseDownOffsetX = gMouseDownX - parseInt(leftNumString,10);

    //The following block gets the Y offset (the difference between where it starts and where it was clicked)
    let topPart = "";
    if(!div.style.top)
        topPart+="0px";     //In case this was not defined as 0px explicitly.
    else
        topPart = div.style.top;
    let topPos = topPart.indexOf("px");
    let topNumString = topPart.slice(0, topPos);    // Get the Y value of the object.
    gMouseDownOffsetY = gMouseDownY - parseInt(topNumString,10);

    window.addEventListener('mousemove', divMove, true);
}

function divMove(e){
    var div = document.getElementById('cursorImage');
    div.style.position = 'absolute';
    let topAmount = e.clientY - gMouseDownOffsetY;
    div.style.top = topAmount + 'px';
    let leftAmount = e.clientX - gMouseDownOffsetX;
    div.style.left = leftAmount + 'px';
}

addListeners();
<div style="height:500px;width:500;background-color:blue;">
    <img src="http://placehold.it/100x100" id="cursorImage" ondragstart="return false;"/>
</div>

This code work with just plain javascript

function addListeners() {
    document.getElementById('image').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown() {
    window.addEventListener('mousemove', divMove, true);
}

function divMove(e){
    var div = document.getElementById('image');
    div.style.position = 'absolute';
    div.style.top = e.clientY + 'px';
    div.style.left = e.clientX + 'px';
}


addListeners();
<div style="height:500px;width:500;background-color:blue;">
  <img src="http://placehold.it/100x100" id="image" />
</div>

Super simple working code with Jquery. Live demo: http://jsfiddle.net/djjL16p2/

<div id="content" style="margin-top: 100px">
    <img id="lolcat" src="http://obeythekitty.com/wp-content/uploads/2015/01/lolcat_airplane.jpg" style="height: 100px; width: 120px; position: absolute;" draggable="false" />
</div>

JS:

$("#lolcat").mousedown(function() {
    $(this).data("dragging", true);
});

$("#lolcat").mouseup(function() {
    $(this).data("dragging", false);
});

$("#lolcat").mousemove(function(e) {
    if (!$(this).data("dragging"))
        return;
    $(this).css("left", e.clientX - $(this).width()/2);
    $(this).css("top", e.clientY - $(this).height()/2);
});

although this is an old question, it has been viewed many times and is high in google search results, so i thought i would provide an answer to this question

dog.onpointerdown           = pd;
cat.onpointerdown           = pd;
document.onpointerup        = ()=>document.onpointermove=null;

function pd(e){  
  e.preventDefault();       //  <-- comment this line and drag the img 
  node                      = e.target;  
  mx                        = e.pageX;
  my                        = e.pageY;
  document.onpointermove    = pm;
}

function pm(e){
  dx                        = e.pageX-mx;
  dy                        = e.pageY-my;
  mx                        = e.pageX;
  my                        = e.pageY;
  x                         = parseInt(node.style.left)+dx;
  y                         = parseInt(node.style.top)+dy;
  node.style.left           = x+'px';
  node.style.top            = y+'px';
}
#dog,#cat {
  position      : absolute;
  width         : 30px;
  height        : 30px;
  border        : 1px solid blue;
}
<div id=dog style='top:50px;left:50px'></div>
<img id=cat style='top:50px;left:100px' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAAVtJREFUKFN10E0ow3EAxvHvb/+NaZMVzUt28FLiprycUA6SUqZGlANXNykXB8mJyEUIJ0UUeQsptMRBXg5m5W0kYYfhb9pf/9l+CgcHnvPn8DyPCIVCkr8iDOyuTmLxDGGrGkD8B8MR2OqtpsZxhVup+wWFQNeCPPvvMJmt2FIy2RlwUpl0wnK4FvGqqlIoRvw3pxg3W7FGn1FiTJwm1HF/7aUmcZ/rwnHEhfdEzo90Ygh4vpq2lwukDsGIgb0bhZw0E+b6VYR7Y1FuT/dTnBzkSY+jMdePjAgEcBmIoriWSEnPQszNTMrDlVHyMyz4vMc0laRij9VQRIT9ezNFXR40TUNo77o8XBgk72GYwMsbssWDea0BNfDIk+KgtGP9B2qavPDdok9V8GpIoqz7gLOJRs5VK3ZHNgXONj7C4e97oqY4tvpcyFgb1W1jHMz2cORTcTY0E2/P+Br5CcV6mGQ0mtQdAAAAAElFTkSuQmCC'>

the above code has one caveat that led me to this question

i was trying to move an image around using the mouse

in the pd function if e.preventDefault() is commented, the image can no longer be dragged although the div is fine, tested in desktop chrome and firefox

it seems the browser specifically prevents dragging images, a pointercancel event is even fired

can anyone shed any light on this behaviour

发布评论

评论列表(0)

  1. 暂无评论