Slider with buttons. How to improve?

余生颓废 提交于 2019-11-27 22:36:45

I don't think you can get around looping through the function or the twitching and trembling if you animate more than one pixel at a time.

But I did try to clean up your code a bit,because you can use +=1px or -=1px with the animation function: (Update: removed the animation function, but you can use +=1px or -=1px for future reference)

$(document).ready(function(){

    var animateTime = 1,
         offsetStep = 5,
         scrollWrapper = $('#wrap');

 //event handling for buttons "left", "right"
 $('.bttR, .bttL')
    .mousedown(function() {
        scrollWrapper.data('loop', true);
        loopingAnimation($(this), $(this).is('.bttR') );
    })
    .bind("mouseup mouseout", function(){
        scrollWrapper.data('loop', false).stop();
        $(this).data('scrollLeft', this.scrollLeft);
    });

    loopingAnimation = function(el, dir){
        if(scrollWrapper.data('loop')){
            var sign = (dir) ? offsetStep : -offsetStep;
            scrollWrapper[0].scrollLeft += sign;
            setTimeout( function(){ loopingAnimation(el,dir) }, animateTime );
        }
        return false;
    };

})

Because I have OCD and don't like slow scrollers, I made a demo with mousewheel functionality and mouse drag and drop functionality. Here is the extra code:

Update: Actually, I think if you don't use the jQuery animate function you get a smoother scroll. I have updated the code above, and the demo.

$('#wrap')  // wrap around content
    .mousedown(function(event) {
        $(this)
            .data('down', true)
            .data('x', event.clientX)
            .data('scrollLeft', this.scrollLeft);
        return false;
    })
    .mouseup(function (event) {
        $(this).data('down', false);
    })
    .mousemove(function (event) {
        if ($(this).data('down') == true) {
            this.scrollLeft = $(this).data('scrollLeft') + $(this).data('x') - event.clientX;
        }
    })
    .mousewheel(function (event, delta) {
        this.scrollLeft -= (delta * 30);
    })
    .css({
        'overflow' : 'hidden',
        'cursor' : '-moz-grab'
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!