Horizontal scrolling with mouse wheel in a div

2019-01-17 07:24发布

问题:

How to scroll horizontal in na div with mouse whell, or drag with jquery?


I've tried draggable, byt in my code it's not usefull.

Now I've got a horizontal scrollbar. Is there a posibility to scroll the content in my div with mouse wheel?

回答1:

Try this for horizontal scrolling with mouse wheel. This is pure 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);
    }
})();

Here's a demo, but with document.body and window as a targetted element: http://rawgit.com/tovic/dte-project/master/full-page-horizontal-scrolling.html



回答2:

I have rewritten the code from the answer by @Anonymous-Lettuce. The width recalculation of the element is skipped as it was unnecessary and sometimes undesirable. This also provides additional feature to pass scroll-amount in px to the plugin.

Use it like this:

$(document).ready(function(){
    $('#your_div').hScroll(100); // You can pass (optionally) scrolling amount
});

Here goes the upgraded plugin 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();
        })
    };
});

Here is the minified version of the same 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()})}});

Here is the JSFiddle



回答3:

I'd like to add a slight improvement to the answer given by @Taufik.

In the context of an es2015 module:

const el = document.querySelector('#scroller');

function scrollHorizontally(e) {
  e = window.event || e;
  e.preventDefault();
  el.scrollLeft -= (e.wheelDelta || -e.detail);
}

function init() {
  if (!el) {
    return;
  }

  if (el.addEventListener) {
    el.addEventListener('mousewheel', scrollHorizontally, false);
    el.addEventListener('DOMMouseScroll', scrollHorizontally, false);
  } else {
    el.attachEvent('onmousewheel', scrollHorizontally);
  }
}

export default init;

The main difference being: el.scrollLeft -= (e.wheelDelta || -e.detail);

Using the e.wheelData directly in the scroll offset means we can have the inertia, so that the scrolling can slow down gradually. I found this worked well for me.

Just use in your code like so (assuming the above code is in a file called scroller.js):

import scroller from './scroller.js';
scroller();


回答4:

Wrote this plugin days ago.

 $.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 );
   });
}

Try it out with

$(document).ready(function(){
     $('#yourDiv').hScroll();
});

The width of the child element of the div should be wider than the parent.

Like 4000 px or something.

 <div id="yourDiv">
       <div style="width: 4000px;"></div>
 </div>


回答5:

In my case I needed to reset the scroll back to normal when the browser was resized, so I modified Izhar's code a bit to make it work for my application:

Initiate hScroll on browser resize:

$(function () {
     $(window).resize($('.horizontal-scroll').hScroll(60));
});

Check if container has white-space property set to 'nowrap' and return if not:

$.fn.hScroll = function (amount) {
    var $this = $(this);
    amount = amount || 120;
    $this.bind('DOMMouseScroll mousewheel', function (event) {
         var isHorizontal = $('.horizontal-scroll').css('white-space') == 'nowrap';
         if (!isHorizontal) return;
         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();
});

};

I use this media query to update the white-space property:

@media (min-width: 768px) {
    .horizontal-scroll { white-space: nowrap !important; }
}

Hope this helps anyone wanting to do the same.



标签: html scroll