Automatic drag and drop with a click

纵然是瞬间 提交于 2021-02-10 16:10:25

问题


I'm looking for an automatic drag and dropper. First, when I click anywhere on the screen, get coordinates, then drag and drop an element with the ID of "ball". using jQuery OR javascript.

I coded a similar script to what I want, but this script got patched when the website's client got updated. This one automatically dragged and dropped when I pressed key 1(keycode 49),

(function () {
  'use strict';

  var mouseX = 0;
  var mouseY = 0;
  var invName = '';
  var timer = 0;
  document.body.addEventListener('mousemove', function (e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
  });
  $('.inventory-box').mousedown(function (e) {invName = e.currentTarget.id;});

  function drop () {
    $('#' + invName).trigger($.Event('mousedown', {button: 0}));
    $('body').trigger($.Event('mouseup', {
      button: 0,
      clientX: mouseX,
      clientY: mouseY
    }));
    timer = setTimeout(drop, 100);
  }

  window.addEventListener('keyup', function (e) {
    if (e.keyCode == 49 && !timer) {
      invName = 'ball';
      drop();
      setTimeout(function () {
        (clearTimeout(timer), timer = 0);
      }, 20);
    }

  });

})();

回答1:


when I click anywhere on the screen, it gets it's coordinates, then drag and drops an element with the ID of "ball"

Here's a very simple vanilla JavaScript method that will locate an element with the ID of "ball" at the cursor location upon click.

The "ball" will follow the cursor until the next click, then the ball will be dropped at the click location.

const ball = document.getElementById('ball');
const ballHalfHeight = Math.round(ball.offsetHeight / 2);
const ballHalfWidth = Math.round(ball.offsetWidth / 2);
let dragState = false;

// move ball to position
function moveBallTo(x, y) {
  ball.style.top = y - ballHalfHeight + 'px';
  ball.style.left = x - ballHalfWidth + 'px';
}

// listen for 'mousemove' and drag ball
function dragListener(evt) {
  const {clientX, clientY} = evt;
  moveBallTo(clientX, clientY);
};

// respond to 'click' events (start or finish dragging)
window.addEventListener('click', (evt) => {
  const {clientX, clientY} = evt;
  moveBallTo(clientX, clientY);
  ball.classList.remove('hidden');

  // handle dragging
  if (!dragState) {
    window.addEventListener('mousemove', dragListener);
  } else {
    window.removeEventListener('mousemove', dragListener);
  }
  dragState = !dragState;
});
.div-ball {
  position: fixed;
  background-color: dodgerblue;
  width: 2rem;
  height: 2rem;
  border-radius: 1rem;
}

.hidden {
  opacity: 0;
}
<body>
  <h4>Click anywhere</h4>
  <div class="div-ball hidden" id="ball"></div>
</body>


来源:https://stackoverflow.com/questions/65995611/automatic-drag-and-drop-with-a-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!