html元素不会在mousedown和mousemove上跟随光标

时间:2019-10-20 11:31:05

标签: javascript html

只要我将鼠标放在该段落上,我就会触发'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>

1 个答案:

答案 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>