只要我将鼠标放在该段落上,我就会触发'mousemove'事件,该事件应使该元素跟随光标,但它是生涩的,只有当我单击它时才移动...
let p = document.querySelector('p');
document.addEventListener('mousedown', function(e) {
document.addEventListener('mousemove', function() {
p.style.left = `${e.clientX}px`;
p.style.top = `${e.clientY}px`
})
})
p {
position: absolute;
left: 0;
top: 0;
}
<p>paragraph</p>
答案 0 :(得分:0)
您应该使用e
事件处理程序提供的事件对象(mousemove
):
const p = document.querySelector('p');
document.addEventListener('mousedown', function(e) {
document.addEventListener('mousemove', function(e) {
p.style.left = `${e.clientX}px`;
p.style.top = `${e.clientY}px`
})
})
p {
position: absolute;
left: 0;
top: 0;
}
<p>paragraph</p>