Jquery滑块定时器

时间:2013-03-21 19:10:25

标签: jquery timer slider

我需要使用jquery为网站创建自定义滑块。到目前为止,我已经设法让它按照我想要的方式运行,如果我点击一个按钮,但我想实现一个自动计时器,以便幻灯片在5秒后切换。

这是我的JS代码:

function MasterSlider() {
    //store the current button ID
    var current_button = $(this).attr('id');

    //reset all the items
    $('#slider ul a').removeClass('slider-button-active');         
    //set current item as active
    $(this).addClass('slider-button-active');


    //scroll it to the right position
    $('.mask').scrollTo($(this).attr('rel'), 850);


    //Check which button is pressed and fade the text accordingly
    if(current_button == "slider_item1")
    {
        $('#slider h3').fadeOut().removeClass('caption_active');
        $('#slider_caption1').fadeIn().addClass('caption_active');
    }
    else if(current_button == "slider_item2")
    {
        $('#slider h3').fadeOut().removeClass('caption_active');
        $('#slider_caption2').fadeIn().addClass('caption_active');
    }
    else if(current_button == "slider_item3")
    {
        $('#slider h3').fadeOut().removeClass('caption_active');
        $('#slider_caption3').fadeIn().addClass('caption_active');      
    }

    //disable click event
       return false;      
}

//append click event to the UL list anchor tag
$('#slider ul a').click(MasterSlider);

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以动态触发click()a元素的setInterval

var intv;
var current = 0;  // STARTING SLIDE(<li>element button) INDEX
var slN = $('#slider li').length; // get number of slides(buttons.. all the same)


 // your function here with
 // clearInterval(intv);
 // in the second line.
 // In third line put:
 // current = $(this).closest('li').index();

// AUTO SLIDE

function auto(){
   intv = setInterval(function() {
        $('#slider ul li').eq( current++%slN  ).find('a').click();
   }, 5000 );       
}
auto(); // to start immediately auto-slide

// PAUSE ON MOUSEOVER

$('#slider').on('mouseenter mouseleave', function( e ){
    var onMouEnt = e.type=='mouseenter' ? clearInterval(intv) : auto() ;
});
  • 感谢current++%slN auto函数将在触发最后一个按钮后循环
  • PAUSE事件检测到您的图库中的事件mouseentermouseleave,并使用三元运算符执行:

$('#slider').on('mouseenter mouseleave', function( e ){ // catch eVENT
    var onMouEnt = e.type=='mouseenter' ?  // if e IS mouseenter
                   clearInterval(intv) :   // clear autoslide interval
                   auto() ;                // else (is mouseleave) run 'auto' fn
});

答案 1 :(得分:-1)

有一个函数setInterval

    function hi(){
        //Your code here
    }

    //set an interval
    setInterval(hi, 30000);