0

有谁知道如何使这个动画左右滚动更顺畅它使用 $.throttle 类,它每毫秒从 github 执行一次有没有人知道另一种方法可以更好地左右平滑jsFiddle我也想做一个 mouseleave 和 mouseout从包装器中将滚动内容动画化回 0px 像素我该怎么做?我的尝试失败了

HTML

<div id="wrapper">
<ul id="scroll-content">
    <li class="item"><img src="http://placehold.it/100x150/09f" /></li>
    <li class="item"><img src="http://placehold.it/100x150/2f2" /></li>
    <li class="item"><img src="http://placehold.it/100x150/234" /></li>
    <li class="item"><img src="http://placehold.it/100x150/342" /></li>
    <li class="item"><img src="http://placehold.it/100x150/312" /></li>
    <li class="item"><img src="http://placehold.it/100x150/131" /></li>
    <li class="item"><img src="http://placehold.it/100x150/111" /></li>
    <li class="item"><img src="http://placehold.it/100x150/222" /></li>
    <li class="item"><img src="http://placehold.it/100x150/333" /></li>
    <li class="item"><img src="http://placehold.it/100x150/122" /></li>
</ul>

CSS:

#wrapper {
width: 100%;
height: 170px;
overflow: hidden;
background-color: red;
}
#scroll-content {
width: 1050px;
}
.item {
float: left;
margin-right: 5px;
list-style-type: none;
}

jQuery:

$(document).ready(function() {
var wrapper = $('#wrapper'),
    content = $('#scroll-content');

wrapper.bind('mouseenter mousemove', $.throttle(200, mousemove));

function mousemove(e) {
    var wrapper_width = wrapper.outerWidth(),
        content_width = content.outerWidth(),
        limits = 50,
        center = wrapper_width / 2,
        wrapper_pos = wrapper.offset(),
        mousePos = Math.min(Math.max(e.pageX,wrapper_pos.left + limits), wrapper_pos.left+wrapper_width-limits);

    //calculate new left margin
    var tmp
    if(e.pageX > center) {
    tmp = (mousePos + 50 - 5) * (content_width - wrapper_width) / wrapper_width;
}else{
         tmp = (mousePos - 50) * (content_width - wrapper_width) / wrapper_width;

        }

    content.stop().animate({
        'margin-left': '-' + tmp + 'px'
    }, 'fast', 'easeOutSine');
}
}); 
4

1 回答 1

0

使用向左滚动动画感觉更好:

js:

$(document).ready(function() {

    
    var wrapper = $('#wrapper'),
        content = $('#scroll-content'),
        width=0.
        wrapper_width=wrapper.outerWidth(),
        w_half=wrapper_width/2;
    var w_left=wrapper.position().left;
    //FIXME wait for images load, to get  width or calculate width other way!
    
    //calculate inner width;
    $('#scroll-content .item').each(function() {
        width+=$(this).width()+5;
    });
    content.css('width',width);
    //
    
    content_width = content.outerWidth();
    wrapper.bind('mouseenter mousemove drag', mousemove);
    function mousemove(e) {
        var mouse_pos=e.pageX-w_left;
        var content_pos=mouse_pos/wrapper_width*content_width-w_half;
        //console.log(e);
        wrapper.stop();
        wrapper.animate({scrollLeft: content_pos},300);
            
    }
});

​</p>

小提琴

可能是某些浏览器不喜欢滚动位置不是 int 或超出范围,但我相信你可以自己修复它

于 2012-12-03T05:56:57.360 回答