Jquery mouse wheel horizontal scrolling with track

2019-04-02 04:04发布

I am using the jquery.mousewheel.js plugin (Github) to build a horizontal scrolling website. It works so far, but I am not able to figure out one problem:

If I am using a trackpad (e.g. on a MacBook Pro) and scroll horizontally with two fingers, depending on how parallel the fingers are positioned, the site will stuck or is confused in which direction it should scroll.

Is there a way to make this horizontal scroll also working smooth?

This is the code I use in the head part:

$(function () {
    $("html, body, *").mousewheel(function (event, delta) {
        this.scrollLeft -= (delta * 5);
        this.scrollRight -= (delta * 5);
        event.preventDefault();
    });
});

Here my jsfiddle with the rebuilt situation: http://jsfiddle.net/mU24m/

1条回答
相关推荐>>
2楼-- · 2019-04-02 04:30

even if this question is a couple of months old, I'll leave something that worked for me.

The idea is that trackpads usually move simultaneously on X and Y, so if we detect a horizontal movement in the scroll wheel listener it is likely a trackpad. Note that you only need to adjust left not both left and right.

$(".container").mousewheel( function(e, delta) {

    if( Math.abs(e.deltaX) ) {
        this.scrollLeft -= (e.deltaX * 20);
    } else {
        this.scrollLeft -= (e.deltaY * 20);
    }

    e.preventDefault();
});

You could also remember that there was a movement on X and then only respond to that axis for a second or so :

var timeout, trackpad = false;

$(".modernlayout .wrapper").mousewheel( function(e, delta) {

    if( trackpad || Math.abs(e.deltaX) ) {
        // probably using trackpad
        // only respond on X axis for a second
        trackpad = true; clearTimeout( timeout );
        timeout = setTimeout(function(){ trackpad = false; }, 1000);
        // use a smaller multiplier
        this.scrollLeft -= (e.deltaX * 10);
    } else {
        // most likely not trackpad
        this.scrollLeft -= (e.deltaY * 20);
    }

    e.preventDefault();

});
查看更多
登录 后发表回答