【问题标题】:jquery image rotatorjquery 图像旋转器
【发布时间】:2011-12-10 12:20:28
【问题描述】:

我有以下 jQuery 横幅旋转器脚本,我想对其进行一些更改,以便横幅每 X 秒旋转一次,即使用户没有单击上一个/下一个按钮。当前代码在这里:

<script type="text/javascript">

    var active_banner_index = 0;

    function banner_next(direction) {
        var banners = $(".banner-content");
        if( banners.length ) {
            var curr = $(banners[active_banner_index]);
            active_banner_index+=direction;
            if( active_banner_index>=banners.length )
                active_banner_index = 0;
            if( active_banner_index<0 )
                active_banner_index = banners.length-1;
            next = $(banners[active_banner_index]);
            curr.fadeOut(1000, 
                function() {
                    next.fadeIn(500);
                }
                );
        }       
    }

    $(document).ready(function() {
        var tbl = $("#mega-hot-deal-666");
        var tag_left = $("#hot-deal-arrow-left");
        var tag_right = $("#hot-deal-arrow-right");

        var banners = $(".banner-content");
        if( banners.length ) {
            $(banners[0]).show();
        }

        pos = tbl.position();
        tag_left.css('z-index',100);
        tag_left.css({ 
                            position: "absolute",
                top: pos.top+67, left: pos.left-37,
                cursor: "pointer"
            });
        tag_right.css('z-index',6);
        tag_right.css({ 
                            position: "absolute",
                top: pos.top+67, left: pos.left+tbl.width()-26,
                cursor: "pointer" 
            });
    active_banner_index = 0;
        tag_left.click( function(){ banner_next(-1); } );
        tag_right.click( function(){ banner_next(1); } );
    });

</script>

我必须添加什么代码才能让横幅自行旋转,而无需等待用户点击按钮?

【问题讨论】:

  • 为什么不用jquery循环插件呢?你想要的功能已经存在

标签: jquery rotator


【解决方案1】:

您需要使用setInterval 来定期调用进度函数。当用户将鼠标悬停在横幅上时,您可能还想暂停它。这是您需要的代码:

$(function(){
    var delay = 4000,
        int;

    // Set interval to progress
    int = setInterval(function(){
        banner_next(1);
    }, delay);

    // OPTIONAL: Pause when hovering over the banner
    $(".banner-content").hover(function(){
        clearInterval(int);
    }, function(){
        int = setInterval(function(){
            banner_next(1);
        }, delay);
    });
});

学习参考:window.setIntervalwindow.clearInterval

【讨论】:

  • 我发现这种方法有时意味着一旦用户离开该区域,幻灯片就会改变,这可能有点刺耳。我建议将间隔设置为变量,然后在 mouseenter 上清除它并在 mouseleave 上再次重新设置。这样,鼠标离开该区域后的延迟始终相同。
  • @N Rohler:谢谢,所以我刚刚在我的下面添加了你的脚本,但什么也没发生。我应该在某个事件上调用该函数吗,也许是在 document.ready 上?
  • @bikey77:此代码正在 document.ready() 上调用 - 请参阅 here。添加一些console.log 值并通过JS控制台调试它。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多