jQuery 鼠标滚轮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6011249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:13:39  来源:igfitidea点击:

jquery mousewheel

jquerymousewheel

提问by user520300

I want to scroll the content of a div with the mousewheel jquery plugin. I have this but its not working. Any thoughts?

我想使用鼠标滚轮 jquery 插件滚动 div 的内容。我有这个,但它不起作用。有什么想法吗?

$(function() {
$('#contentBox').bind('mousewheel', function(event, delta) {
   if (delta > 0) {
        $('#contentBox').css('top', parseInt($('#contentBox').css('top'))+40);
    } else {
        $('#contentBox').css('top', parseInt($('#contentBox').css('top'))-40);
    }
  return false;
}); 
}); 

采纳答案by Bobby Hyman

Just a guess : does adding + 'px' to the CSS value fix things? Actually, what does 'media' refer to?

只是猜测:将 + 'px' 添加到 CSS 值是否可以解决问题?实际上,“媒体”指的是什么?

UPDATE

更新

OK, I've had a chance to test your code and it all looks good, presuming you've set the CSS up properly. Have you actually assigned a value for topon #contentBox already? Without an existing value, parseInt($('#contentBox').css('top'))will return NaN. Here's the code that I used:

好的,我有机会测试您的代码,一切看起来都不错,假设您已经正确设置了 CSS。你真的top已经为#contentBox赋值了吗?如果没有现有值,parseInt($('#contentBox').css('top'))将返回NaN. 这是我使用的代码:

$(function() {
    $('#contentBox').bind('mousewheel', function(event, delta) {

        $('#contentBox').css('top', parseInt($('#contentBox').css('top')) + (delta > 0 ? 40 : -40));

        return false;
    });
});

#contentBox { height: 4em; background-color: #eee; border: 1px solid #ccc; position: absolute; top: 100px; width: 200px; }

<div id="contentBox"></div>

Note that I've used the ternary operator to simplify/reduce the code a bit, but this is just to keep the size of this answer down a bit, and is entirely optional. I've also just used some test CSS there to see what I'm doing; I'm sure yours is different!

请注意,我使用了三元运算符来稍微简化/减少代码,但这只是为了将这个答案的大小缩小一点,并且完全是可选的。我还在那里使用了一些测试 CSS 来查看我在做什么;我相信你的不一样!

回答by ruvan

$('#contentBox').bind('mousewheel DOMMouseScroll', function(event) {
  event.preventDefault();
  var delta = event.wheelDelta || -event.detail;
  $(this).css({'top': $(this).position().top + (delta > 0 ? '+=40' : '-=40')});
}); 

http://www.adomas.org/javascript-mouse-wheel/

http://www.adomas.org/javascript-mouse-wheel/

回答by Simone Gianni

If you are using jQuery 1.6, you can write:

如果你使用 jQuery 1.6,你可以这样写:

$('#contentBox').css('top','+=40');

and forget about it.

忘记它。

Obviously, you still need CSS to properly declare #contentBoxto be in absolute positioning and all the rest.

显然,您仍然需要 CSS 正确声明#contentBox处于绝对定位和所有其他位置。