1

I'm attempting to create a horizontal scroller simliar to this. http://www.k2.pl/

I made a prototype here. http://jsfiddle.net/Uu3aP/1

I looked into the carousel plugins but none function how I would like.

I'm just curious how I perform speed calculation based on the x position to the left and right and maybe use an easing method for the sides.

This is where I am currently at, any assistance would be appreciated.

HTML

<div id="scroll">
<div id="scrollContainer">
<ul>
    <li><img src="http://placehold.it/350x350" alt="" /></li>
    <li><img src="http://placehold.it/350x350" alt="" /></li>
    <li><img src="http://placehold.it/350x350" alt="" /></li>
    <li><img src="http://placehold.it/350x350" alt="" /></li>
    <li><img src="http://placehold.it/350x350" alt="" /></li>
</ul>
</div>

CSS

body {
    margin: 0;
}
#scroll {
    width: 100%;
    overflow: hidden;
}
#scrollContainer * {
    float: left;
    list-style: none;
    margin: 0;
    padding: 0;
}

JAVASCRIPT

$(document).ready(function() {

    var $totalwidth = 0;
    var $paneTarget = $('#scroll');
    var $paneContainer = $('#scrollContainer');
    var $this = $(this);
    var $w = $this.width();

    $paneTarget.find('li').each(function() {
        $totalwidth += $this.width();
        $paneContainer.width($totalwidth);
    });

    $paneTarget.on('mousemove', function(e) {
        if ((e.pageX) < $w / 2) {
            $paneTarget.stop().scrollTo( {top:'0', left:'-=100'}, 200, {easing: 'linear'});
        } else if ((e.pageX) > ($w / 2)) {
            $paneTarget.stop().scrollTo( {top:'0', left:'+=100'}, 200, {easing: 'linear'});
        }
        else {
            $paneTarget.stop();
        }
    });

});
4

1 回答 1

2

我用你的小提琴演奏了一下,想出了这个:小提琴

我没有使用 scrollTo 插件或 jQuery 的动画,而是创建了一个自定义动画方法,该方法使用 setInterval 调用。

// This gets called from the setInterval and handles the animating
function animationLoop() {
    var dx = targetX - posX,    // Difference
        vx = dx * EASING;       // Velocity

    // Add velocity to x position and update css with new position
    posX += vx;
    $paneContainer.css({left: posX});             
}

targetX 在 mousemove 处理程序中更新

// Calculate the new x position for the scroll container
targetX = Math.round((event.pageX / windowWidth) * maxScroll);

[编辑]
要处理窗口大小调整,您基本上只需要重置 windowWidth 和 maxScroll 变量:

$(window).on('resize', function() {
    windowWidth = $(window).width();
    maxScroll = -(containerWidth - windowWidth);

    // OPTIONAL:
    // Move scrollpane to original position on resize
    targetX = 0;
    // Start animating if it's not already
    // Probably better in a new function: duplicate code from mousemove..
    if (!animInterval) {
        animInterval = setInterval(animationLoop, 1000 / FPS);
    }
});

更新了 jsfiddle

于 2013-06-03T22:25:40.980 回答