我正在寻找一个自动拖放器。首先,当我单击屏幕上的任意位置时,获取坐标,然后拖放 ID 为“ball”的元素。使用 jQuery 或 JavaScript。
我编写了一个与我想要的类似的脚本,但是当网站的客户端更新时,这个脚本得到了修补。当我按下1
键(键码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);
}
});
})();
最佳答案
when I click anywhere on the screen, it gets it's coordinates, then drag and drops an element with the ID of "ball"
这是一个非常简单的普通 JavaScript 方法,它将在单击时在光标位置定位 ID 为“ball”的元素。
“球”会跟随光标移动,直到下一次点击,然后球就会落在点击位置。
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>
关于javascript - 单击即可自动拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65995611/