【问题标题】:Infinite horizontal slider showing more than one slide with pause animation on hover无限水平滑块显示不止一张幻灯片,悬停时有暂停动画
【发布时间】:2014-01-13 20:56:04
【问题描述】:

我正在尝试制作一个从右向左滑动并一次显示 4 张幻灯片的无限滑块。我的意思是无限的,比如当幻灯片 1 被隐藏时,它会移动到最后一张幻灯片旁边的末尾。

这是我的html:

<div id="slider">
    <div class="slide">slide 1</div>
    <div class="slide">slide 2</div>
    ... up to slide 6
</div>

我是 jquery 的新手,所以我不知道如何完成这项工作。

  • 我认为滑动应该在 setInterval() 内。
  • 使用 animate() 来制作 margin-left 的动画。为 margin-left 设置一个负值以将其向左滑动并隐藏。
  • 获取隐藏的幻灯片并将其移至最后一张

jquery:

var currentSlide = 0;
setInterval(function(){
    $('.slide').animate({marginLeft:-$('.slide').width()});     
    $('.slide').eq(currentSlide++).insertAfter($('.slide').last())
}, 2000);

每张幻灯片都包含带有背景图像的文本。这就是我现在所拥有的,滑动很丑陋。我还想设置我想用 jquery 显示多少,所以我不必编辑我的 css,我还想在你将鼠标悬停在滑块上时集成类似暂停的东西。请帮忙,谢谢。

【问题讨论】:

    标签: javascript jquery html slider jquery-animate


    【解决方案1】:

    我认为您对如何完成这项工作有一个好主意。但是您的代码需要更正。

    您正在为所有 '.slide' 制作动画,因为它们都是内联的,您只需为第一张幻灯片制作动画,之后的所有内容都会跟随:

    $('.slide').first().animate({marginLeft:-$('.slide').width()});
    

    您还同时对其进行动画处理和移动。您只需在动画完成后移动它。

    $('.slide').first().animate({
        marginLeft:-$('.slide').width()
    }, 'slow', function(){
        //once completely hidden, move this slide next to the last slide
        //and reset the margin-left to 0
        $(this).appendTo($(this).parent()).css({marginLeft: 0});       
    });
    

    这里是jsfiddle


    要解决滑动问题,我们需要为幻灯片添加一个包装器,并将其宽度设置为所有幻灯片的总宽度。

    新标记:

    <div id="slider">
        <div id="slide-container">
            <div class="slide">slide 1</div>
            <div class="slide">slide 2</div>
        </div>
    </div>
    

    jQuery:

    var w = $('#slider').width() / 4;
    var l = $('.slide').length;
    //set each slide width
    $('.slide').width(w);  
    //set the container width to fix the animation sliding issue
    $('#slide-container').width(w * l)
    

    要在悬停在滑块上时添加暂停,您只需 clearInterval 并将其重置以继续:

    function slider(){
        $('.slide').first().animate({
            marginLeft: -w 
        }, 'slow', function () {
            $(this).appendTo($(this).parent()).css({marginLeft: 0});
        });
    }
    
    //setInterval on DOM ready
    var timer = setInterval(slider, 2000);
    
    $('#slider').hover(function(){
        //mouse in, clearinterval to pause
        clearInterval(timer);
    },function(){
        //mouse out, setinterval to continue
        timer = setInterval(slider, 2000);
    });
    

    查看此更新的jsfiddle

    【讨论】:

    • 哦,谢谢。使用 appendTo 移动最后的幻灯片看起来很整洁。
    • 在你的 jsfiddle 中,最后一张幻灯片没有滑动,它只是在其他人完成滑动时弹出。我正在寻找一个平滑的幻灯片,您是否也可以帮助我使用我编辑问题的暂停滑块方法先生。
    • 是的,我也注意到了这一点。我也更新了我的答案。希望能回答一切。干杯!
    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多