jQuery Grab Content and Scroll page horizontally

2019-05-11 07:28发布

问题:

My goal is to grab content x and scroll page horizontally while mouse is moving until mouse stops (mouseup event), similar to a tablet swipe action.

Seems easy enough.. Get clientX on mousedown, scrollLeft by ClientX while moving, Turn off mousemove function when done.

I've been playing with it for awhile and can't get the scroll effect I'm looking for..

What am I doing wrong here?

$('#thediv').on('mousedown', function(event) {  
    var e = event;   

    $('#thediv').on('mousemove',function(event){ 
        new_e = event; 
        $('html, body').stop().animate({
            scrollLeft: new_e.clientX  
        }, 300);   
        return false;  
     }); 

    $('#thediv').on('mouseup', function() { 
        $('#thediv').off('mousemove');  
    }); 
}); 

http://jsfiddle.net/mD7mu/

回答1:

$('#greendiv').on('mousedown', function(e) {
    $('#greendiv').on('mousemove', function(evt) {
        $('html,body').stop(false, true).animate({
            scrollLeft: e.pageX - evt.clientX
        });
    });
});

really close. simply subtracting the clientX from the pageX , and using false,true in the stop function will give you the desired effect, I think.

here's the fiddle!