如何捕获点击加拖动事件

时间:2018-10-16 15:34:05

标签: javascript

我想捕获单击加拖动事件,例如浏览器文本选择,我称之为ondrag事件:

function drag() {
  console.log("being dragged.");
}
<p ondrag="drag()" > Hello World!</p>

但是当我单击并拖动文本时没有调用它,知道为什么吗?

2 个答案:

答案 0 :(得分:1)

似乎您实际上并不想使用拖动事件,而想要使用mousemove事件。这样的事情将达到目的:

var p = document.querySelector('p');

p.addEventListener('mousedown', mouseDownListener, true);
window.addEventListener('mouseup', mouseUpListener, true);

function mouseMoveListener(e) {
  console.log('moving mouse');
}

function mouseDownListener(e) {
  console.log('mouse down');
  window.addEventListener('mousemove', mouseMoveListener, true);
}

function mouseUpListener(e) {
  console.log('mouse up');
  window.removeEventListener('mousemove', mouseMoveListener, true);
}
<p>Hello World!</p>

答案 1 :(得分:0)

向p标签添加draggable =“ true”属性以使其起作用

检查此链接以获取更多详细信息-https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable

   function drag() {
       console.log("being dragged.");
    }
    <p ondrag="drag()" draggable="true"> Hello World!</p>
    
 

codepen供参考-https://codepen.io/nagasai/pen/KGZoRm