我试图让Syn.js进行程序化鼠标移动以在我的应用程序的规格中使用。
我需要跟踪并测试mouseenter
和mouseleave
。做了一个简单的规范,但无法使它工作,没有事件被解雇。
指向我可能遗失的内容?或如何使事件发生?
我的测试用例:
( jsFiddle :http://jsfiddle.net/g1wjkjw5/)
JS
document.getElementById('target').addEventListener('mouseenter', log);
document.getElementById('target').addEventListener('mouseleave', log);
var events = {};
function log(e) {
console.log(e.type); // never fires... :/
events[e.type] = true;
}
setTimeout(function () {
syn.move({
from: {clientX: 400, clientY: 400},
to: {clientX: 50, clientY: 50},
duration: 1000
}, document.body);
console.log('Syn fired');
}, 200);
setTimeout(function () {
console.log(events); // this gets empty
}, 2000);
CSS
div#target {
background: #ccf;
border: 1px solid black;
}
HTML
<script src="https://rawgit.com/bitovi/syn/master/dist/syn.js"></script>
<div id="target" style="float: left; padding: 100px;"></div>
答案 0 :(得分:2)
Mozilla probably won't let you
查看Syn.js源代码,您所追踪的事件根本不会被模拟。
jQuery does what the others have suggested
请记住,最初的鼠标输入/离开是Internet Explorer专有的,jQuery模拟它。它最近才变得无处不在。 1 2
这是一个jsfiddle using a modified Syn.js来实现您的要求。
只需更改事件名称:
if (last !== el && el && last) {
var options = syn.helpers.extend({}, point);
options.relatedTarget = el;
syn.trigger(last, 'mouseleave', options);
options.relatedTarget = last;
syn.trigger(el, 'mouseenter', options);
}
答案 1 :(得分:1)
试试这个
document.getElementById('target').addEventListener('mouseover', function(){
console.log('mouse inside');
});
document.getElementById('target').addEventListener('mouseout', unction(){
console.log('mouse left');
});
var events = {};
setTimeout(function () {
syn.move({
from: {clientX: 600, clientY: 300},
to: {clientX: 50, clientY: 50},
duration: 1000
}, document.body);
console.log('Syn fired');
}, 200);
setTimeout(function () {
console.log(events);
}, 2000);
答案 2 :(得分:0)
根据他们的文档,syn库会为悬停事件触发事件mouseover
和mouseout
:
document.getElementById('target').addEventListener('mouseover', log);
document.getElementById('target').addEventListener('mouseout', log);
小提琴:
http://jsfiddle.net/g1wjkjw5/2/
如果您真的想将它们记录为mouseenter / mouseleave,可以在日志函数中转换这些事件
function log(e) {
if (e.type == "mouseover") {
events["mouseenter"] = true
} else if (e.type == "mouseout") {
events["mouseleave"] = true
} else {
events[e.type] = true;
}
}
http://jsfiddle.net/g1wjkjw5/4/
编辑:
为了捕获实际的鼠标[enter | leave]事件,您可以捕获mouseover / mouseout事件并将它们转换为正确的事件对象:
document.getElementById('target').addEventListener('mouseover', transformEvent);
document.getElementById('target').addEventListener('mouseout', transformEvent);
function transformEvent(e) {
var newEvent = false;
if (e.type == "mouseover") {
newEvent = "mouseenter";
} else if (e.type == "mouseout") {
newEvent = "mouseleave";
}
if (newEvent) {
e.stopImmediatePropagation();
e.preventDefault();
var event = new MouseEvent(newEvent, {
'view': window,
'bubbles': true,
'cancelable': true
});
e.toElement.dispatchEvent(event);
}
}