如何绑定mousemove scroll并将all调整为一个函数

目前,当鼠标移动时,我“做东西”。 但是,如果用户调整浏览器大小或向下滚动浏览器,我也想做同样的事情。 jQuery(document).bind(’mousemove’,function(e){var x,y; x = e.pageX; // x coord y = e.pageY; // y coord //其他东西});

我试着去做

jQuery(document).bind('mousemove resize scroll',function(e){... 

但它不起作用。 我也试过了

 jQuery(document, window).bind('mousemove resize scroll',function(e){... 

但它也没有用。

我也知道你可以使用检测滚动

 $(window).scroll(function(){ 

并检测resize

 $(window).resize(function() { 

但是,如果我使用这些检测,我将不会有“e”参数来获取鼠标的x和y坐标

如何将所有3个事件全部绑定到一个函数中?

谢谢

您仍然在滚动和resize方法中有事件数据。 尝试使用3个处理程序将代码包装到单个函数中。 on()方法需要jQuery 1.7+

 function reusable(eData){ // Heres what you want to do every time } $(document).on({ mousemove: function(e) { reusable(e); }, scroll : function(e) { reusable(e); } ); $(window).on({ resize : function(e) { reusable(e); } }); 

编辑

事件应该在正确的对象windowdocument否则您将获得意外的值。

来自你的评论:

问题是当resize或滚动事件并且正在破坏我的应用程序时,e.pageX未定义

那么,当你知道它们undefined时,为什么要使用当前的对象属性? 为什么不使用全局变量并在其中保留最后一个值?

在JsBin中的实例

 var clientX = 0, clientY = 0, screenX = 0, screenY = 0, pageX = 0, pageY = 0; // bind the events in the correct objects jQuery(window).bind('resize',function(e) { getBindingValues(e); }); jQuery(document).bind('mousemove scroll',function(e) { getBindingValues(e); }); // your one-function function getBindingValues(e) { clientX = e.clientX ? e.clientX : clientX; clientY = e.clientY ? e.clientY : clientY; screenX = e.screenX ? e.screenX : screenX; screenY = e.screenY ? e.screenY : screenY; pageX = e.pageX ? e.pageX : pageX; pageY = e.pageY ? e.pageY : pageY; $("#hello").html( "*** Safe values ***
" + "mouse: X." + clientX + " Y." + clientY + "
" + "page: X." + pageX + " Y." + pageY + "
" + "screen: X." + screenX + " Y." + screenY + "

" + "*** More values ***
" + "window: W." + $(window).width() + " H." + $(window).height() + "
" + "type: " + e.type + "" ); }

你可以在下面比较mousemove上的e (事件)对象并scroll

在滚动

在此处输入图像描述

在mousemove上

在此处输入图像描述