如何将mousemove滚动绑定并全部调整为一个函数 [英] How to bind mousemove scroll and resize all into one function

查看:103
本文介绍了如何将mousemove滚动绑定并全部调整为一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently, I "do stuff" when the mouse moves. However, I also want to do the exact same thing if the user resizes the browser or scrolls down the browser. jQuery(document).bind('mousemove',function(e){ var x, y; x = e.pageX; // x coord y = e.pageY; // y coord //other stuff });

我试着做

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

但是没有用.我也尝试过

but it didn't work. I also tried

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

但是它也不起作用.

我还知道您可以使用来检测滚动

I also know that you can detect scroll using

$(window).scroll(function(){

并使用

$(window).resize(function() {

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

But the if I use those detections, I won't have the "e" argument to get the x and y coordinates of the mouse

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

How do I bind all 3 events all into one function?

谢谢

推荐答案

滚动和调整大小方法中仍然具有事件数据.尝试将您的代码包装到具有3个处理程序的单个函数中. on()方法需要jQuery 1.7 +

You do still have the event data in the scroll and resize methods. Try wrapping your code into a single function with 3 handlers. The on() method requires 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中,否则您将获得意外的值.

The events should be in their correct objects window and document or you will get unexpected values.

这篇关于如何将mousemove滚动绑定并全部调整为一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆