【问题标题】:Simulate next button click with jQuery使用 jQuery 模拟下一个按钮单击
【发布时间】:2012-01-10 04:21:55
【问题描述】:

不确定这是否可行,但我的网站上有一个幻灯片,当一个按钮单击相关幻灯片时,它会滑入。

我想要做的是添加一个计时器,以便在 3 秒后单击下一个按钮,使我的幻灯片自动滑动。

$('#button a').click(function(){
    var integer = $(this).attr('rel');
    $('#myslide .cover').animate({left:-720*(parseInt(integer)-1)})  /*----- Width of div mystuff (here 160) ------ */
    $('#button a').each(function(){
    $(this).removeClass('active');
        if($(this).hasClass('button'+integer)){
            $(this).addClass('active')}
    });


});

我添加了一个小提琴... http://jsfiddle.net/5jVtK/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    最简单的方法是使用 setTimeout(延迟后发生一次)或 setInterval(每隔一段时间发生一次)。

    setTimeout( function() { $( '#button a' ).trigger( 'click' ) }, 3000 );

    setInterval( function() { $( '#button a' ).trigger( 'click' ) }, 3000 );

    实现此功能后,您可能需要考虑其他一些细节,例如当用户的鼠标悬停在下一个按钮或幻灯片上时停止自动进度(因为这意味着对当前显示的内容感兴趣)和在鼠标移出时恢复自动前进。

    下一步:听起来你需要弄清楚如何动态地找到正确的按钮来触发,以便在多张幻灯片中继续前进。这是一种方法:

    `

    function click() {
        // Find the button for the next slide in relationship to the currently active button
        var $next = $( '#button' ).find( '.active' ).next( 'a' );
    
        // If there isn't one, go to the beginning
        if ( ! $next.length ) {
            $next = $( '#button' ).find( 'a' ).first();
        }
    
        // Trigger the click
        $next.trigger( 'click' );
    
        setTimeout(click, 3000);
    }
    
    setTimeout(click, 3000);
    

    这是一个小提琴的链接,展示了这一点:

    http://jsfiddle.net/5jVtK/1/

    【讨论】:

    • Liam - 我已经添加到我的解释中,以帮助解决我认为是您的其他问题...动态查找您需要的下一个按钮。希望对您有所帮助。
    【解决方案2】:

    你可以通过 jQuery 触发元素的click 事件

    $('#button a').click();
    

    要以 3 秒为间隔,请使用 setInterval()

    function simulateClick(){
        $('#button a').click();
    };
    
    setInterval(simulateClick, 3000);
    

    【讨论】:

    • 这就是我目前正在做的事情,是否可以自动化它,就像模拟点击下一个按钮一样?
    • @Liam:我扩展了我的答案。请参见上文。
    • 谢谢@Colin,我目前有 5 个按钮,当函数运行时,它会模拟所有按钮都被点击,有没有办法实现 .next() 而不运行所有按钮?
    【解决方案3】:

    这样的事情应该可以工作。这样我们就可以间隔运行一个函数,并且单击也会触发相同的函数。计时器永远不需要激活按钮,只需激活按钮也激活的功能。

    $(document).ready(function() {
       var timer = setInterval( slideFunction, 5000);
    
        $('#button a').click(function(){
         slideFunction();
        });
        function slideFunction(){
            var integer = $('#button a').attr('rel');
            $('#myslide .cover').animate({left:-720*(parseInt(integer)-1)})  /*----- Width of div mystuff (here 160) ------ */
            $('#button a').each(function(){
                $(this).removeClass('active');
                if($(this).hasClass('button'+integer)){
                $(this).addClass('active')}
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多