Smooth grabbing

梦想的初衷 提交于 2019-12-03 16:46:18

You can get the flash look by using an easing equation sometimes referred to as zeno's paradox.

position += (destination - position) / damping

I modified your jsFiddle to make use of it: Have a look

If you'd like me to give a more detailed description of zeno's paradox, let me know and I'll post one here with an image or two.

I think this is the best you can get with jQuery: [Demo]

jQuery.fx.interval = 1; // since v1.4.3
var photos = $(".photos");
var scrollLeft = photos[0].scrollLeft;
var $el = $(photos[0]);
var lastTime = +new Date();


$(window).mousemove(function(event){
    var now = +new Date();
    var elapsed = now - lastTime;
    if (dragging && elapsed > 10) {
        scrollLeft += x - event.clientX;
        $el.stop().animate({scrollLeft:  scrollLeft}, 300, "easeOutCubic");
        x = event.clientX;
        lastTime = +new Date();
    }
});

$(window).mouseup(function(event){
    dragging = false;
    $el.stop().animate({scrollLeft:  scrollLeft}, 500, "easeOutCubic");
});

Note, all the possible (slight) sluggishness can't be corrected at the moment, because it's related to image rendering performance of modern browsers. Test - simple linear animation, no events, no jQuery

Try replacing this line:

photos[0].scrollLeft += x - event.clientX;

with this (Updated demo):

photos.animate({ scrollLeft : '+=' + (x - event.clientX) }, 12, 'easeOutCirc');

Note that I clicked on jQuery UI to include the easing options. Also, it is very jumpy in the jFiddle (using Firefox) demo, but it doesn't do that at all when I test it on my desktop or if I look at that demo in Chrome. Ideally using the easing function without using jQuery animate would be best. But this should give you an idea.

var dragging = false;
var x, startX, startTime, stopTime;
var photos = $(".photos");

photos.mousedown(function(event){
    dragging = true;
    startX = x = event.clientX;
    startTime = new Date();
    event.preventDefault();
});

$(window).mousemove(function(event){
    if (dragging) {
        photos[0].scrollLeft += x - event.clientX;
        stopTime = new Date();
        x = event.clientX;
    }
});

$(window).mouseup(function(event){
    dragging = false;
    var left = photos[0].scrollLeft;
    var dx = (startX - event.clientX);
    var time = stopTime - startTime;
    var speed =time/dx;
    photos.animate({ scrollLeft : (left + dx*time/500), easing :'swing' }, 100/time*1000);  
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!