Jquery文本旋转器问题

问题描述 投票:1回答:1

我需要显示带有文本的第一个容器,然后显示并隐藏上一个/下一个有一些延迟,但问题是如果我给一个类.active到第一个.container文本js代码删除和addClass再次到第一个元素但我需要跳过第二次.container ..只是它在第一次迭代时产生延迟6s而不是3s

//Create a var to store the index of red element
var count = -1;
function AddRedClass() {
  var boxes = $('.topinfo-bar .container');
  var boxLength = boxes.length - 1;
  //Check if the actual item isn't more than the length then add 1 otherway restart to 0
  count < boxLength ? count++ : count=0;
  //Remove the class and add it to the new target
  boxes.removeClass('active').eq(count).addClass('active');
}

setInterval(AddRedClass, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container {if $item@first}active{/if}">
                <div class="topinfo-bar__wrapper">
                    <div class="topinfo-bar__icon">
                        <img src="./img/info.png" alt="info">
                    </div>
                    <div class="topinfo-bar__content">
                        <p class="default-paragraph">
                            {$item->info}
                        </p>
                    </div>
                </div>
            </div>
javascript jquery html css
1个回答
0
投票

考虑到你当前的标记,JS不应该做太多,因为$('.topinfo-bar .container')不匹配任何东西。但除此之外,你很亲密。

使用实际匹配标记中的元素的选择器让我们有一个变量来保存activeIndex(可以很容易地控制/检查和设置外部脚本,如果你需要......)并在我们总是放置active时推进这个索引在集合的activeIndex类上的类,并从其余类中删除它:

let duration = 420, // these are miliseconds
  activeIndex = 0;  // first item to activate

function activateNext() {
  let boxes = $('.boxes > div');

  // activate current item
  boxes.removeClass('active').eq(activeIndex).addClass('active');
  
  // increase activeIndex and make reset at end of collection 
  if (++activeIndex >= boxes.length) activeIndex = 0;
  
  // run the function again after duration
  setTimeout(function() {
    activateNext(activeIndex);
  }, duration)
}

// start the loop
$(window).on('load', activateNext);
.active {color: red;}
.boxes div {
  transition: color .1s linear;
  font-size: 1.5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
  <div>one</div>
  <div>two</div>
  <div>three</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.