jquery图像旋转器

时间:2011-10-18 22:54:04

标签: jquery rotator

我有以下jQuery banner rotator脚本,我想稍微更改它,以便横幅每X秒旋转一次,即使用户没有点击prev / next按钮也是如此。目前的代码在这里:

<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>

我需要添加哪些代码才能让横幅自行旋转,而无需等待用户点击按钮?

1 个答案:

答案 0 :(得分:2)

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

$(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