如何在na div中使用鼠标滚轮进行水平滚动,或者使用jquery进行拖动?
我尝试过draggable,但在我的代码中它没有用。
现在我有了一个水平滚动条。是否可以使用鼠标滚轮滚动div中的内容?
发布于 2013-03-12 00:43:01
尝试使用鼠标滚轮进行水平滚动。这是纯JavaScript:
(function() {
function scrollHorizontally(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.getElementById('yourDiv').scrollLeft -= (delta * 40); // Multiplied by 40
e.preventDefault();
}
if (document.getElementById('yourDiv').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('yourDiv').addEventListener('mousewheel', scrollHorizontally, false);
// Firefox
document.getElementById('yourDiv').addEventListener('DOMMouseScroll', scrollHorizontally, false);
} else {
// IE 6/7/8
document.getElementById('yourDiv').attachEvent('onmousewheel', scrollHorizontally);
}
})();下面是一个演示,但是使用document.body和window作为目标元素:https://taufik-nurrohman.github.io/dte-project/full-page-horizontal-scrolling.html
发布于 2015-07-21 15:05:31
我已经根据@Anonymous-Lettuce的答案重写了代码。跳过元素的宽度重新计算,因为这是不必要的,有时也是不希望的。这也提供了额外的功能,将px中的scroll-amount传递给插件。
像这样使用它:
$(document).ready(function(){
$('#your_div').hScroll(100); // You can pass (optionally) scrolling amount
});这里是升级后的插件jquery.hscroll.js
jQuery(function ($) {
$.fn.hScroll = function (amount) {
amount = amount || 120;
$(this).bind("DOMMouseScroll mousewheel", function (event) {
var oEvent = event.originalEvent,
direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
position = $(this).scrollLeft();
position += direction > 0 ? -amount : amount;
$(this).scrollLeft(position);
event.preventDefault();
})
};
});下面是同一个jquery.hscroll.min.js的精简版本
jQuery(function(e){e.fn.hScroll=function(l){l=l||120,e(this).bind("DOMMouseScroll mousewheel",function(t){var i=t.originalEvent,n=i.detail?i.detail*-l:i.wheelDelta,o=e(this).scrollLeft();o+=n>0?-l:l,e(this).scrollLeft(o),t.preventDefault()})}});这里是
发布于 2013-02-26 19:22:50
几天前写了这个插件。
$.fn.hScroll = function( options )
{
function scroll( obj, e )
{
var evt = e.originalEvent;
var direction = evt.detail ? evt.detail * (-120) : evt.wheelDelta;
if( direction > 0)
{
direction = $(obj).scrollLeft() - 120;
}
else
{
direction = $(obj).scrollLeft() + 120;
}
$(obj).scrollLeft( direction );
e.preventDefault();
}
$(this).width( $(this).find('div').width() );
$(this).bind('DOMMouseScroll mousewheel', function( e )
{
scroll( this, e );
});
}使用以下命令尝试
$(document).ready(function(){
$('#yourDiv').hScroll();
});div的子元素的宽度应该比父元素宽。
比如4000px之类的。
<div id="yourDiv">
<div style="width: 4000px;"></div>
</div>https://stackoverflow.com/questions/11700927
复制相似问题