JS设置元素 鼠标拖拽 且 可以以鼠标位置滚轮放大缩小

JS设置元素 鼠标拖拽 且 可以以鼠标位置滚轮放大缩小

作者: qq2402398917, 支持油猴脚本定制, 爬虫

已经封装成函数了, 直接用就ok

function SetMovable(Ele)
{
     let scale = 1;
      let originX = 0;
      let originY = 0;
      let isDragging = false;
      let startX, startY;

      Ele.addEventListener('wheel', (event) => {
          event.preventDefault();

          const rect = Ele.getBoundingClientRect();
          const offsetX = event.clientX - rect.left;
          const offsetY = event.clientY - rect.top;

          const delta = Math.sign(event.deltaY) * -0.1;
          const newScale = Math.min(Math.max(0.5, scale + delta), 3);

          originX = (originX - offsetX) * (newScale / scale) + offsetX;
          originY = (originY - offsetY) * (newScale / scale) + offsetY;

          scale = newScale;

          Ele.style.transform = `translate(${originX}px, ${originY}px) scale(${scale})`;
      });

      Ele.addEventListener('mousedown', (event) => {
        event.stopPropagation();
           event.preventDefault();
          isDragging = true;
          startX = event.clientX;
          startY = event.clientY;
          Ele.style.cursor = 'grabbing';
      });

      Ele.onclick = event => event.stopPropagation();

      window.addEventListener('mouseup', (event) => {
        event.stopPropagation();
           event.preventDefault();
          isDragging = false;
          Ele.style.cursor = 'grab';
      });

      window.addEventListener('mousemove', (event) => {
        event.stopPropagation();
           event.preventDefault();
          if (!isDragging) return;

          const dx = event.clientX - startX;
          const dy = event.clientY - startY;

          originX += dx;
          originY += dy;

          startX = event.clientX;
          startY = event.clientY;

          Ele.style.transform = `translate(${originX}px, ${originY}px) scale(${scale})`;
      });

      Ele.reset = function() {
          scale = 1;
          originX = 0;
          originY = 0;
          Ele.style.transform = `translate(0, 0) scale(${scale})`;
      }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值