Jquery mouse wheel horizontal scrolling with trackpad

北城余情 提交于 2019-12-05 06:16:21

问题


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:


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();

});


来源:https://stackoverflow.com/questions/20332722/jquery-mouse-wheel-horizontal-scrolling-with-trackpad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!