【问题标题】:How to make two elements appear and disappear on a top of each other in an infinite loop如何使两个元素在无限循环中彼此重叠出现和消失
【发布时间】:2017-02-22 04:32:30
【问题描述】:

我试图让标题一消失,然后标题二出现和消失,标题一出现在一个循环中。我的代码的问题是,标题二只出现了很短的时间,并且在标题一出现之前,空白屏幕至少会出现 2-3 秒。

JS:

var h1 = $('.header_one');
var h2 = $('.header_two');

setInterval(function(){
    h1.fadeOut(1000);
    h2.fadeIn(1000);
    h2.fadeOut(2000, function() { h1.fadeIn(); });
}, 4000);

HTML:

<h1 class="header_one"> HEADER ONE </h1>
<h2 class="header_two"> HEADER TWO </h2>

CSS:

h1, h2 {
    z-index: 10;
    position: relative;
}     

h2 {display: none;}

还有一个问题:当标题二消失时,我在h1和h2下面的两个链接,设置为位置:相对;移到页面顶部。

【问题讨论】:

  • 我相信在 jquery 中使用动画效果更好
  • 为什么,如果你不介意解释,Alvaro?

标签: javascript jquery css animation


【解决方案1】:

这是一种方法:jsfiddle

$("#box1").hide();


function animate() {
  $("#box2").fadeOut(1000, function() {
    $("#box1").fadeIn(1000, function() {
      $("#box1").fadeOut(1000, function() {
        $("#box2").fadeIn(1000, animate);
      });
    });
  });
}

animate();
div {
  position: absolute;
  left: 20px;
  top: 20px;
  background: red;
  width: 50px;
  height: 50px;
}

div:nth-child(2) {
  left: 30px;
  top: 30px;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1"></div>
<div id="box2"></div>

【讨论】:

    【解决方案2】:

    标题消失时链接向上移动的原因是fadeInfadeOut 正在操纵display 属性,将其从文档流中删除。只有visibility 属性会保留元素的位置并为其保留空间。

    假设您的 2 个标题在样式方面看起来相同,为什么不只使用一个并在设置颜色/透明度动画的同时更改其中的文本?

    但是如果你真的想在给定代码的情况下按顺序触发它们,那么你需要做你在最后一行所做的事情,其中​​一个是当另一个完成时的回调;但是,这不会解决您的链接向上移动的问题。

    这是一种非常讨厌/糟糕的做法,但它确实有效......

    setInterval(function(){
        $('h1').fadeOut(function(){
            $('h2').fadeIn();
        });
    }, 4000);
    
    setInterval(function(){
        $('h2').fadeOut(function(){
            $('h1').fadeIn();
        });
    }, 8000);
    

    【讨论】:

      【解决方案3】:

      这是我使用 jquery animate 循环的选项:

      https://jsfiddle.net/vbw8jLko/

      var h1 = $('.header_one');
      var h2 = $('.header_two');
      
      function loop(){
      console.log('llop');
          $( ".header_one" ).stop().css('opacity', 0).show().animate({opacity:1}, 700).delay(700).animate({
          opacity: 0
        }, 1000, function(){
        $(this).hide();
        $( ".header_two" ).stop().css('opacity', 0).show().delay(100).animate({
          opacity: 1
        }, 1000).delay(700).animate({opacity:0}, 1000, function(){
        $(this).hide(); loop()});
        });
      
      }
      
      loop();
      

      期待喜欢它:)

      【讨论】:

        猜你喜欢
        • 2018-09-09
        • 2016-12-08
        • 1970-01-01
        • 2013-03-16
        • 2018-09-07
        • 2015-08-14
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多