如何使用pageX和pageY模拟mousemove事件

时间:2019-04-27 21:28:11

标签: javascript html

我想模拟一个鼠标移动事件。设置如下

我有这个元素

<div class="target"></div>

在此测试设置中,跟随鼠标的是:DEMO

我已经对mousedown事件进行了模拟(单击按钮)。生成此事件的代码如下:

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

source

但是如何创建伪造的movemove事件?因为我还需要为其提供pageX和pageY。如上所示创建活动时如何提供此信息?

1 个答案:

答案 0 :(得分:0)

我已经更新了您的示例代码,以显示如何创建mousemove事件。请注意,您的代码使用了不推荐使用的document​.create​Event(),并且您应该考虑将其替换为较新的MouseEvent,这是我在添加的代码部分中使用的。

const target = document.querySelector('.target');

document.querySelector('main')
  .addEventListener('mousemove', (e) => {
    if (e.clientY > 60) {
      target.style.top = (e.clientY - 25) + 'px';
    }
      target.style.left = (e.clientX - 25) + 'px'; 
  });

target.addEventListener('mousedown', () => {
   console.log('mouse down');
})

const butt = document.querySelector('.sim-move');
butt.addEventListener('click', () => {

 let evt = new MouseEvent("mousemove", {
    clientX: 150,
    clientY: 5,
    bubbles: true,
    cancelable: true,
    view: window
  });
  
  let canceled = !target.dispatchEvent(evt);  

});

const butt1 = document.querySelector('.sim-down');
butt1.addEventListener('click', () => {
    triggerMouseEvent(target, 'mousedown');
});
function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}
html, body, main {
  height: 100%;
  padding: 0;
  margin: 0;
}

body {
  margin: 20px;
  }

main {
  display: block;
  border: 1px solid #000;
  height: calc(100% - 42px);
}

div {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50px;
  height: 50px;
  background-color: green;
}
<button class="sim-move">Simulate mousemove</button>
<button class="sim-down">Simulate mousedown</button>
<main>
  <div class='target'></div>
</main>