我正在浏览器中创建一个图像编辑器,我已经完成了所有控件的代码。现在我想映射热键和鼠标按钮。键盘很简单,但鼠标不是。
我需要检测鼠标何时在画布div上以及鼠标滚轮在其上方移动时。鼠标在部分上并不难,它与我遇到麻烦的鼠标滚轮绑定。
我尝试了jQuery.scroll
但是如果方向盘下的div
设置为自动滚动,那么只有接缝才能工作。我的canvas
不是。它的偏移量是通过我的脚本控制的。
注意事项:
<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>
答案 0 :(得分:28)
一个非常简单的实现看起来像:
$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta/120 > 0) {
$(this).text('scrolling up !');
}
else{
$(this).text('scrolling down !');
}
});
});
答案 1 :(得分:15)
与此同时,mousewheel
事件已被弃用,并被wheel
取代。
MDN Docs mousewheel 说:
请勿使用此轮事件。
此界面是非标准的,已弃用。它仅用于非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
}
});
});
来自 Connell Watkins的comment - &#34;你能用120解释除法吗?&#34; ,
MSDN上有一些细节:
onmousewheel事件是暴露wheelDelta属性的唯一事件。此属性指示车轮按钮旋转的距离,以120的倍数表示。正值表示车轮按钮已旋转远离用户。负值表示滚轮按钮已朝向用户旋转。
我在方法中遗漏了delta / 120
部分,因为IMO没有任何好处。向上滚动为delta > 0
,向下delta < 0
。简单。
答案 2 :(得分:3)
您是否尝试过鼠标滚轮插件?
答案 3 :(得分:2)
使用jquery绑定鼠标滚轮的一个简单示例....
<!DOCTYPE html>
<html>
<head>
<title>Mouse Wheel</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<style type='text/css'>
body { text-align: center; }
#res
{
margin-top: 200px;
font-size: 128px;
font-weight: bold;
}
</style>
<script type='text/javascript'>
$(document).ready(function(){
var num = 0;
$(document).bind('mousewheel',function(e){
if (e.wheelDelta == "120")
{
$("#res").text(++num);
}
else
{
$("#res").text(--num);
}
});
});
</script>
</head>
<body>
<div id="res">0</div>
</body>
</html>
答案 4 :(得分:1)
e.wheelDelta对我没用。
这有效:
$(document).ready(function(){
$('#foo').bind('mousewheel',function(e){
if (e.originalEvent.wheelDelta == 120){
//mouse up
}
else
{
//mouse down
}
});
});
&#13;