在纯js中移动(拖动/平移)和缩放对象(图像或div)

san*_*a B 5 javascript move zooming pan drag

我正在编写一个小脚本,使对象(div 或 img)在给定框架内可移动和缩放。

但是,我遇到了一些我不太确定的问题,因为我是 javascript 初学者-因此将不胜感激解释为什么会出现这些问题。

问题:

  1. 调用函数start_drag()while_drag()然后stop_drag()返回undefined- 为什么会这样?应该返回什么?
  2. 图像的拖动和移动无法正常工作 - 我必须单击一次然后开始移动,而不是单击鼠标按钮并开始移动图像。虽然我将mousedown事件绑定到图像。我做错了什么?
  3. 为什么移动部分在移动设备上不起作用(缩放有效!)?

请看我的小提琴:https : //jsfiddle.net/pow4ngbw/15/

Bug*_*Bug 7

现在工作正常,主要是图像 css 但发现了几个错误(请参阅新的 img 属性),还添加了一些调整以使拖动更平滑。

 
    var img_ele = null,
      x_cursor = 0,
      y_cursor = 0,
      x_img_ele = 0,
      y_img_ele = 0;
    
    function zoom(zoomincrement) {
      img_ele = document.getElementById('drag-img');
      var pre_width = img_ele.getBoundingClientRect().width, pre_height = img_ele.getBoundingClientRect().height;
      img_ele.style.width = (pre_width * zoomincrement) + 'px';
      img_ele.style.height = (pre_height * zoomincrement) + 'px';
      img_ele = null;
    }
    
    document.getElementById('zoomout').addEventListener('click', function() {
      zoom(0.5);
    });
    document.getElementById('zoomin').addEventListener('click', function() {
      zoom(1.5);
    });
    
    function start_drag() {
      img_ele = this;
      x_img_ele = window.event.clientX - document.getElementById('drag-img').offsetLeft;
      y_img_ele = window.event.clientY - document.getElementById('drag-img').offsetTop;
      
    }
    
    function stop_drag() {
      img_ele = null;
    }
    
    function while_drag() {
      var x_cursor = window.event.clientX;
      var y_cursor = window.event.clientY;
      if (img_ele !== null) {
        img_ele.style.left = (x_cursor - x_img_ele) + 'px';
        img_ele.style.top = ( window.event.clientY - y_img_ele) + 'px';
        
          console.log(img_ele.style.left+' - '+img_ele.style.top);
    
      }
    }
    
    document.getElementById('drag-img').addEventListener('mousedown', start_drag);
    document.getElementById('container').addEventListener('mousemove', while_drag);
    document.getElementById('container').addEventListener('mouseup', stop_drag);
Run Code Online (Sandbox Code Playgroud)
 #drag-img {
      cursor: move;
      position: relative;
      width: 500px;
      height: 500px;
    }
    
    #container {
      overflow: hidden;
      background: red;
      height: 500px;
      width: 500px;
    }
    
    .button {
      width: 200px;
      height: 50px;
    }
Run Code Online (Sandbox Code Playgroud)
 <div id="container">
      <img ondragstart="return false" id="drag-img" src="http://www.patsoy.com/p/2015/09/geometric-patterns-f03phtdx.jpg" />
    </div>
    <input type="button" id="zoomout" class="button" value="Zoom out">
    <input type="button" id="zoomin" class="button" value="Zoom in">
  
Run Code Online (Sandbox Code Playgroud)

  • 当你第一次开始拖动时,我注意到一个轻微的跳跃,在你的 start_drag 事件中将 +8 添加到 x_img_ele 和 y_img_ele (2认同)