Javascript 具有超时和值的函数++不根据需要更改活动类

Javascript 具有超时和值的函数++不根据需要更改活动类,javascript,jquery,settimeout,Javascript,Jquery,Settimeout,这就是函数。它确实能很好地改变图片,淡入淡出。这是一个幻灯片,.bullet只是一个圆圈,点击它你可以跳转到一张特定的图片 顺便说一下,此功能可以让您跳转到您选择的任何图片: function anim() { clearTimeout(animTimeout); $('#wrap .bullet').removeClass('active'); imageindex++;

这就是函数。它确实能很好地改变图片,淡入淡出。这是一个幻灯片,.bullet只是一个圆圈,点击它你可以跳转到一张特定的图片

顺便说一下,此功能可以让您跳转到您选择的任何图片:

function anim() {
            clearTimeout(animTimeout);              
            $('#wrap .bullet').removeClass('active');
            imageindex++;
            $('#wrap .bullet:nth-child('+ imageindex +')').addClass('active');
            $('#wrap .images img').fadeOut();
            $('#wrap .images img:nth-child('+ imageindex +')').fadeIn();
            if($('#wrap .images img').length == imageindex) {
                imageindex = 0;
            }

    animTimeout = setTimeout(anim, 1500);
}
但是,我希望当前图片子弹处于活动状态,这样你就不会跳转到前一张图片上,等等


动画功能给我的效果是,在第一张幻灯片上,所有的.bullet-s都有一个活动类,从第二张幻灯片开始,它们不再有活动类,直到它再次回到第一张幻灯片。为什么会这样?如果imageindex在增长,我看不出有什么理由会有这样的行为。。。谢谢你的帮助

两件事可能是你问题的根源

1-动画可能会触发多次 2-imageindex不稳定

我建议您将console.log'anim with'+imageindex语句添加到anim的开头,以检查调用anim的次数和imageindex的值


还要确保在使用imageindex的任何其他js函数之前声明imageindex变量。

在您的情况下,我将替换您的全局变量imageindex,这不是您试图实现的目标所必需的

将其替换为以下代码:

        $('#wrap .bullets a').click(function(e){
  e.preventDefault();
            $('#wrap .images img').stop().attr('style', '');
            imageindex = parseInt($(this).data('i') );
            anim();
        });

实际上,我找到了一个解决方案-使用第n个子选择器不起作用,但是$$'wrap.bullet'.getimageindex.addClass'active';做
var animTimeout = null;

function anim() {
    clearTimeout(animTimeout);
    var activeIndex = $('#wrap .bullet.active') // select the active bullet
                         .removeClass('active') // remove its 'active' class
                         .next().addClass('active') // put 'active' class to the next item
                         .index(); // retrieve the new active item index
    if (activeIndex < 0) {
        // if end of list reached, put it on the first item
        activeIndex = $('#wrap .bullet').first().addClass('active').index();
    }
    // cancel previous animations before starting fadeOut and fadeIn
    $('#wrap .images img').stop().fadeOut().eq(activeIndex).fadeIn();
    animTimeout = setTimeout(anim, 1500);
}

$('#wrap .bullets a').click(function(e) {
    $('#wrap .images img').stop().attr('style', '');
    $('#wrap .bullet').removeClass('active');
    $('#wrap .bullet').eq($(this).parent().index() - 1).addClass('active');
    anim();
});