如何使两个元素在无限循环中显示和消失在彼此的顶部

时间:2017-02-21 13:49:38

标签: javascript jquery css animation

我试图让标题消失,然后标题2出现并消失,标题一出现在循环中。我的代码的问题是,标题2仅在非常短的时间内出现,并且空白屏幕在标题1出现之前至少持续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;}

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

3 个答案:

答案 0 :(得分:1)

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

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

但是如果你真的想按照你的代码顺序解雇它们,那么你需要做你在最后一行做的事情,其中​​一个是另一个完成时的回调;但是,这不会解决您的链接问题。

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

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

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

答案 1 :(得分: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 :(得分:1)

我可以选择使用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();

期待它:)