简体   繁体   English

使用纯 JavaScript 拖动和移动图像效果不佳

[英]Drag and move image using plain JavaScript doesn't work well

I've gone ahead and implemented a drag feature for my image that should move the image in whichever direction you drag the image.我已经为我的图像实现了一个拖动功能,该功能应该在您拖动图像的任何方向上移动图像。 I;m not sure whats wrong with it, if its slow and needs to be throttled, if my maths off, or I'm just plain doing something wrong.我不知道它有什么问题,如果它很慢并且需要限制,如果我的数学不好,或者我只是做错了什么。 I made a minimal viable example.我做了一个最小可行的例子。 Any help would be really appreciated.任何帮助将非常感激。

Here's a codepen.这是一个代码笔。

HTML HTML

<div class="img-cntnr">
  <img class="my-img" src="http://www.fillmurray.com/g/900/900" alt="" />
</div>

CSS CSS

.img-cntnr {
  position: relative;
  border: dodgerBlue solid 20px;
  width: 500px;
  height: 500px;
  overflow: hidden;
}

.img-cntnr img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 0;
  bottom: 0;
  margin: auto;
  cursor: -webkit-grab;
}

JS JS

  var images = document.getElementsByClassName('my-img');
  var imgCntnrs = document.getElementsByClassName('img-cntnr');
  var dragImgMouseStart = {};
  var imgCntnrH;
  var imgCntnrW;

  function mousedownDragImg(e) {
    dragImgMouseStart.x = e.pageX;
    dragImgMouseStart.y = e.pageY;
    imgCntnrH = imgCntnrs[0].offsetHeight;
    imgCntnrW = imgCntnrs[0].offsetWidth;

    // add listeners for mousemove, mouseup
    window.addEventListener('mousemove', mousemoveDragImg);
    window.addEventListener('mouseup', mouseupDragImg);
  }

  function mousemoveDragImg(e) {
    var diffX = -1 * (dragImgMouseStart.x - e.pageX);
    var diffY = -1 * (dragImgMouseStart.y - e.pageY);
    var oldLeft = isNaN(parseFloat(images[0].style.left)) ? 0 : parseFloat(images[0].style.left);
    var newLeft = oldLeft + diffX / imgCntnrW;
    images[0].style.left = newLeft + '%';
    var oldTop = isNaN(parseFloat(images[0].style.top)) ? 0 : parseFloat(images[0].style.top);
    var newTop = oldTop + diffY / imgCntnrH;
    images[0].style.top = newTop + '%';
    console.log(newLeft, newTop);
  }

  function mouseupDragImg(e) {
    window.removeEventListener('mousemove', mousemoveDragImg);
    window.removeEventListener('mouseup', mouseupDragImg);
  }

  for (var i = images.length - 1; i >= 0; i--) {
    // make images unselectable
    images[i].ondragstart = function() {
      return false;
    };
  };

  images[0].addEventListener('mousedown', mousedownDragImg);

There were a few rectifications needed in your code.您的代码需要进行一些更正。

  • First of all all DOM access must be done through requestAnimationFrame() .首先必须通过requestAnimationFrame()完成所有 DOM 访问。 Then i had to refactor the code for a better performance.然后我不得不重构代码以获得更好的性能。 Moving DOM objects are best done by CSS3 transform: translate(x,y);移动 DOM 对象最好通过 CSS3 transform: translate(x,y);
  • Then I had to refactor the code further.然后我不得不进一步重构代码。 I modified the semantics a little bit.我稍微修改了语义。 In order to move the image element we will "only" alter the transform: translate(x,y);为了移动图像元素,我们将“仅”改变transform: translate(x,y); CSS property as we move the mouse.移动鼠标时的 CSS 属性。 So we only need this CSS property's initial values.所以我们只需要这个 CSS 属性的初始值。 Since you have chosen to center the over-sized image horizontally by doing left: 50%;由于您选择通过执行left: 50%;将过大的图像水平left: 50%; (first move the image to the right up until it's left edge is at the containing div's half width) then transform: translateX(-50%); (首先将图像向右移动,直到它的左边缘位于包含 div 的半宽处)然后transform: translateX(-50%); (move the image to the left as much as haft of it's width) we can easily see that our translateX value is half of the image width (-50%). (将图像向左移动到宽度的一半)我们可以很容易地看到我们的translateX值是图像宽度的一半 (-50%)。 The translateY value has never been modified so it remains as 0. I have changed this property into transform: translate(-50%, 0); translateY值从未被修改,因此它保持为 0。我已将此属性更改为transform: translate(-50%, 0); for consistency.为了一致性。 Well, now lets calculate our initial x value for the translate(x,y) .好吧,现在让我们计算translate(x,y)初始x值。 The image.getBoundingClientRect() tool is very useful to get the width of the image element in integers. image.getBoundingClientRect()工具对于以整数形式获取image元素的宽度非常有用。

So please see the below snippets for the rest.因此,请参阅下面的片段以了解其余部分。 It's pretty self explanatory.这是不言自明的。

Also at JSBin and CodePen同样在 JSBin 和 CodePen

https://jsbin.com/bawalebowi/1/edit?css,js,output https://jsbin.com/bawalebowi/1/edit?css,js,output

http://codepen.io/omerillo/pen/EKWOZQ http://codepen.io/omerillo/pen/EKWOZQ

 var image = document.getElementsByClassName('my-img')[0], imgCntnrs = document.getElementsByClassName('img-cntnr'), dragImgMouseStart = {}, lastDiff = {x:0, y:0}, initialPos = image.getBoundingClientRect(), currentPos = {x: -initialPos.width/2, y: 0}; function mousedownDragImg(e) { e.preventDefault(); dragImgMouseStart.x = e.clientX; dragImgMouseStart.y = e.clientY; currentPos.x += lastDiff.x; currentPos.y += lastDiff.y; lastDiff = {x: 0, y: 0}; window.addEventListener('mousemove', mousemoveDragImg); window.addEventListener('mouseup', mouseupDragImg); requestAnimationFrame(function(){ image.style.transform = "translate(" + (currentPos.x + lastDiff.x) + "px," + (currentPos.y + lastDiff.y) + "px)"; }); } function mousemoveDragImg(e) { e.preventDefault(); lastDiff.x = e.clientX - dragImgMouseStart.x; lastDiff.y = e.clientY - dragImgMouseStart.y; requestAnimationFrame(function(){ image.style.transform = "translate(" + (currentPos.x + lastDiff.x) + "px," + (currentPos.y + lastDiff.y) + "px)"; }); } function mouseupDragImg(e) { e.preventDefault(); window.removeEventListener('mousemove', mousemoveDragImg); window.removeEventListener('mouseup', mouseupDragImg); } image.addEventListener('mousedown', mousedownDragImg);
 .img-cntnr { position: relative; border: dodgerBlue solid 10px; border-radius: 10px; width: 250px; height: 250px; overflow: hidden; margin: 0; padding:0; } .img-cntnr img { position: absolute; left: 50%; transform: translate(-50%, 0); top: 0px; bottom:0px; margin: auto; padding: 0; cursor: -webkit-grab; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="img-cntnr"> <img class="my-img" src="http://www.fillmurray.com/g/900/900" alt="" /> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM