问题描述
我正在寻找自动拖放器。首先,当我单击屏幕上的任意位置时,获取坐标,然后拖放 ID 为“ball”的元素。使用 jQuery 或 javascript。
我编写了一个与我想要的类似的脚本,但是当网站的客户端更新时,这个脚本得到了修补。当我按下 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);
}
});
})();
解决方法
当我点击屏幕上的任何地方时,它会获取它的坐标,然后拖放一个 ID 为“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);
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>