首页 > 解决方案 > How to drag a scaled element

问题描述

I'm making a dragged image. It works as it should. I also have buttons that scale the image. after scaling, the drug works but it cuts the position. I can't find the right words to describe this behavior.At the first movement the image changes its position slightly

what calculations do I need to do too. to get a smooth drag, after scaling an element.

https://codesandbox.io/s/laughing-tree-1zqhf?file=/src/App.js

Thank you in advance

标签: javascripthtmlcssreactjsfrontend

解决方案


您必须保留初始 X 并仅计算移动的差异。

const onMouseDown = e => {
    e.persist();
    var initialX = e.pageX;
    const onMouseMove = ev => {
      var newX = initialX - ev.pageX;
      setX(x - newX);
    };


    const onMouseUp = () => {
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", onMouseUp);
    };

    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("mouseup", onMouseUp);
  };

分叉沙箱链接:https ://codesandbox.io/s/compassionate-ishizaka-kvmnk?file=/src/App.js


推荐阅读