【问题标题】:Jquery animation: fade in element, fade out, then stopJquery动画:淡入元素,淡出,然后停止
【发布时间】:2021-09-28 08:49:11
【问题描述】:

我是 Jquery 动画的新手。
我有两个元素要淡入,顺序需要是这样的: 加载时,元素 1 可见。 5 秒后淡出。
淡入元素 2,停止(从那时起,元素 2 在屏幕上保持可见)。
目前,它可以工作,但会不断循环。
这是我的代码:

$(document).ready(function() {
  $('.no-js').removeClass('no-js'); /* JS is enabled */
  var currentContent = 0;
  var nbContent = $('.content').length;
  var tempo;
  $('.content').eq(currentContent).removeClass('off').addClass('on');

  function changeContent() {
    currentContent++;
    if (currentContent < nbContent) {
      $('.on').toggleClass('off').toggleClass('on');
      $('.off').eq(currentContent).toggleClass('off').toggleClass('on');
    } else {
      currentContent = 0;
      $('.on').toggleClass('off').toggleClass('on');
      $('.off').eq(currentContent).toggleClass('off').toggleClass('on');
    }
  }
  tempo = setInterval(changeContent, 5000);
});
.container-content {
  padding: 190px 0 0 6px;
  width: 90%;
  line-height: 1.3em;
  z-index: 0;
  text-align: center;
  word-wrap: break-word
}

.container-content p {
  margin: 3px 0 0;
}

#content-2 {
  position: absolute;
  top: 190px;
  left: 2px;
}

#content-2 .button {
  position: absolute;
  top: 160px;
  left: -20px;
}

.on {
  opacity: 1;
  -webkit-transition: all .5s ease-in;
  -moz-transition: all .5s ease-in;
  -ms-transition: all .5s ease-in;
  -o-transition: all .5s ease-in;
  transition: all .5s ease-in;
  -webkit-transition-delay: 2s;
  -moz-transition-delay: 2s;
  -ms-transition-delay: 2s;
  -o-transition-delay: 2s;
  transition-delay: 2s;
  z-index: 2
}

.off {
  opacity: 0;
  -webkit-transition: all 2s ease-out;
  -moz-transition: all 2s ease-out;
  -ms-transition: all 2s ease-out;
  -o-transition: all 2s ease-out;
  transition: all 2s ease-out;
  z-index: 1
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div id="container-content" class="container-content no-js">
  <div id="content-1" class="content off">
    <p> Some text here
    </p>
  </div>
  <div id="content-2" class="content off">
    <p> More text here
    </p>
  </div>
</div>

谁能帮我解决这个问题?

【问题讨论】:

  • 它连续工作 - 第一个猜测(不要看得太仔细)是你应该将setInterval 更改为setTimeout,所以它只运行一次。
  • 仔细观察,您似乎期望超过 2 个元素,因此希望不断更新它们。如果您希望它在最后停止,则在 } else { 内添加 clearTimeout(tempo) 或从 if 内调用 setTimeout

标签: jquery css animation


【解决方案1】:

为 setTimeout 更改 setInterval 效果很好,感谢@freedom-mn!

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多