越过div时绑定到滚轮

Rob*_*rst 26 javascript jquery javascript-events

我正在浏览器中创建一个图像编辑器,我已经完成了所有控件的代码.现在我想映射热键和鼠标按钮.键盘很简单,但鼠标不是.

我需要检测鼠标何时在画布div上以及鼠标滚轮在其上方移动时.鼠标在部分上并不难,它与我遇到麻烦的鼠标滚轮绑定.

我试过jQuery.scroll但是只有当div轮子设置为自动滚动时才能使用.我canvas的不是.它的偏移量是通过我的脚本控制的.

注意事项:

  • 我使用jQuery作为我的基础.
  • 我不是实际滚动任何东西,我正在尝试将滚动轮绑定和事件而不实际滚动.

结构体

<div id="pageWrap">
    [page head stuff...]
    <div id="canvas">
        [the guts of the canvas go here; lots of various stuff...]
    <div>
    [page body and footer stuff...]
</div>
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 28

一个非常简单的实现看起来像:

$(document).ready(function(){
    $('#foo').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta/120 > 0) {
            $(this).text('scrolling up !');
        }
        else{
            $(this).text('scrolling down !');
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

http://www.jsfiddle.net/5t2MN/5/

  • 我认为它应该是:`e.originalEvent.wheelDelta`.我在Chrome上测试过它. (14认同)
  • 你能用120来解释分裂吗? (8认同)
  • 任何想要使用**jQuery 1.7 +**的人都应该使用Esteban建议的`e.originalEvent.wheelDelta`.你可以在这里查看小提琴:[http://jsfiddle.net/KyleMit/25btn/](http://jsfiddle.net/KyleMit/25btn/)原因是jQuery事件处理程序中的事件对象没有反映实际提出的事件.wheelData是一个非标准的事件属性,不再传递给jQuery事件,但仍然可以从触发调用的原始源事件中获得. (8认同)

Mar*_*ann 15

重要更新01/2015 - 不推荐使用mousewheel事件:

与此同时,该mousewheel事件已被弃用并替换为wheel.

用于鼠标滚轮的MDN文档说:

不要使用此轮事件.

此接口是非标准的,已弃用.它仅用于非Gecko浏览器.而是使用标准车轮事件.


现在你应该使用类似的东西:

// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
    var el = document.createElement('div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
        el.setAttribute(eventName, 'return;');
        isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
}

$(document).ready(function() {
    // Check which wheel event is supported. Don't use both as it would fire each event 
    // in browsers where both events are supported.
    var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';

    // Now bind the event to the desired element
    $('#foo').on(wheelEvent, function(e) {
        var oEvent = e.originalEvent,
            delta  = oEvent.deltaY || oEvent.wheelDelta;

        // deltaY for wheel event
        // wheelData for mousewheel event

        if (delta > 0) {
            // Scrolled up
        } else {
            // Scrolled down
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

PS

来自康奈尔沃特金斯评论- "你能用120解释分裂吗?" ,MSDN
上有一些细节:

onmousewheel事件是暴露wheelDelta属性的唯一事件.此属性指示车轮按钮旋转的距离,以120的倍数表示.正值表示车轮按钮已旋转远离用户.负值表示车轮按钮已朝向用户旋转.

delta / 120在方法中遗漏了部分,因为IMO没有任何好处.滚动向上delta > 0和向下滚动delta < 0.简单.