`mousemove` and triggering a custom event

删除回忆录丶 提交于 2019-12-13 02:49:45

问题


In a mousemove event:

$(document).on('mousemove', function( e ){
    console.log( e.pageX );
    console.log( e.pageY );
});

as you can see, we can use pageX and pageY to get the x and y co-ordinates of mouse position. But, what I want is to trigger a custom event of mine on mousemove and would like to get these pageX and pageY values in that custom event of mine. To be more clear, what I would like to do is:

$(document).on('mousemove', function(){
    $(document).trigger('myevent');
});

$(document).on('myevent', function( e ){
    // console.log( e.pageX );
    // console.log( e.pageY );
});

Is there any way to access these pageX and pageY in myevent?


回答1:


.trigger() allows to pass additional data via its arguments. You can call

$(document).on('mousemove', function( event ){
    $(document).trigger('myevent', event);
});

Now you have access to the whole original event object within your custom event code.




回答2:


Another option is to create a custom event like

$(document).on('mousemove', function(e) {
  var event = $.Event('myevent', {
    pageX: e.pageX,
    pageY: e.pageY
  });
  $(document).trigger(event);
});

$(document).on('myevent', function(e) {
  log(e.pageX + ':' + e.pageY)
});

var log = function(message) {
  var $log = $('#log');
  $log.html(message)
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="log"></div>


来源:https://stackoverflow.com/questions/26782333/mousemove-and-triggering-a-custom-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!