我得到了这个jsfiddle
$('#test').trigger('mousemove', [Handler],{type:'BLUE!'});
当我通过触发方法“鼠标移动”时,我尝试获取红色方块的坐标。
这可能吗?
$(function() {
$("#test").on("mousemove", youCantHandleTheFunc);
$('#button').click(function() {
$('#test').trigger('mousemove', {
type: 'custom mouse move'
});
});
$('#test2').mousemove(function() {
$('#test').trigger('mousemove', {
type: 'BLUE!'
});
});
});
function youCantHandleTheFunc(e, customE) {
if (customE != undefined) {
e = customE;
}
$('#result').html(e.type);
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
$("span:first").text("( event.pageX, event.pageY ) : " + pageCoords);
}
#test {
width: 100px;
height: 100px;
background-color: red;
}
#test2 {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='test'></div>
<div id='test2'></div>
<p>
<button type='button' id='button'>touch me to trigger the mousemove event on the block</button>
</p>
<p id='result'></p>
<span>Move the mouse over the div.</span>
答案 0 :(得分:0)
尝试将document.createEvent()
,MouseEvent.initMouseEvent()
替换为.trigger()
虽然
.trigger()
模拟事件激活,但完成了 合成事件对象,它不能完美复制一个 自然发生的事件。
$(function() {
function triggerMouseMove() {
var e = document.createEvent("MouseEvents");
e.initMouseEvent("mousemove", true, true, window);
document.getElementById("test").dispatchEvent(e);
}
$("#test").on("mousemove", youCantHandleTheFunc);
$('#button').click(function() {
triggerMouseMove()
});
$('#test2').mousemove(youCantHandleTheFunc);
function youCantHandleTheFunc(e, customE) {
console.log(e, customE)
// if (customE != undefined) {
// e = customE;
// }
$('#result').html(e.type);
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
$("span:first").text("( event.pageX, event.pageY ) : " + pageCoords);
}
})
#test {
width: 100px;
height: 100px;
background-color: red;
}
#test2 {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id='test'></div>
<div id='test2'></div>
<p>
<button type='button' id='button'>touch me to trigger the mousemove event on the block</button>
</p>
<p id='result'></p>
<span>Move the mouse over the div.</span>