越过div时绑定到滚轮
我正在浏览器中创建一个图像编辑器,我已经完成了所有控件的代码。 现在我想映射热键和鼠标按钮。 键盘很简单,但鼠标不是。
我需要检测鼠标何时在canvasdiv上以及鼠标滚轮在其上方移动时。 鼠标在部分上并不难,它与我遇到麻烦的鼠标滚轮绑定。
我尝试了jQuery.scroll
但只有当轮子下的div
设置为自动滚动时才能使用。 我的canvas
不是。 它的偏移量是通过我的脚本控制的。
注意事项:
- 我使用jQuery作为我的基础。
- 我不是实际滚动任何东西,我正在尝试将滚动轮绑定和事件而不实际滚动。
结构体
[page head stuff...] [the guts of the canvas go here; lots of various stuff...] [page body and footer stuff...]
重要更新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 } }); });
PS
来自康奈尔沃特金斯的评论 – “你能用120解释分裂吗?” ,
有关MSDN的一些细节:
onmousewheel事件是暴露wheelDelta属性的唯一事件。 此属性指示车轮按钮旋转的距离,以120的倍数表示。正值表示车轮按钮已旋转远离用户。 负值表示车轮按钮已朝向用户旋转。
我在我的方法中省略了delta / 120
部分,因为IMO没有任何好处。 向上滚动是delta > 0
且delta < 0
。 简单。
一个非常简单的实现看起来像:
$(document).ready(function(){ $('#foo').bind('mousewheel', function(e){ if(e.originalEvent.wheelDelta/120 > 0) { $(this).text('scrolling up !'); } else{ $(this).text('scrolling down !'); } }); });
你试过mousewheel插件吗?
使用jquery绑定鼠标滚轮的简单示例….
Mouse Wheel 0
e.wheelDelta对我不起作用。
这工作:
$(document).ready(function(){ $('#foo').bind('mousewheel',function(e){ if (e.originalEvent.wheelDelta == 120){ //mouse up } else { //mouse down } }); });