admin管理员组

文章数量:1391999

I have below my JAVASCRIPT code which change between 2 words every 2.5 seconds and I want to add fading to the transition between the words in the array it uses. I know that I need to use Jquery but how do I implement it in this recursive function? Any ideas?

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}
.banner-right h2 {
  font-size: 50px;
  font-weight: 300;
  color: #ffffff;
  margin: 15px 0 45px 0;
}
<h2 id="changeText">Data Scientist</h2>

I have below my JAVASCRIPT code which change between 2 words every 2.5 seconds and I want to add fading to the transition between the words in the array it uses. I know that I need to use Jquery but how do I implement it in this recursive function? Any ideas?

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}
.banner-right h2 {
  font-size: 50px;
  font-weight: 300;
  color: #ffffff;
  margin: 15px 0 45px 0;
}
<h2 id="changeText">Data Scientist</h2>

Share Improve this question edited Jan 6, 2020 at 21:20 Goran Stoyanov 2,3111 gold badge22 silver badges32 bronze badges asked Jul 9, 2015 at 9:34 user3882752user3882752 2731 gold badge5 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Since you are using Native JavaScript you could use CSS transitions and classList.

Something like:

CSS

#changeText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}

JavaScript

function change() {
    elem.classList.add('hide');
    setTimeout(function () {
        elem.innerHTML = text[counter];
        elem.classList.remove('hide');
        counter++;
        if (counter >= text.length) {
            counter = 0;
        }
    }, 500);
}

Demo:

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
    elem.classList.add('hide');
    setTimeout(function () {
        elem.innerHTML = text[counter];
        elem.classList.remove('hide');
        counter++;
        if (counter >= text.length) {
            counter = 0;
        }
    }, 500);
}
#changeText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}
<h2 id="changeText">Data Scientist</h2>

Note: I used !important in the CSS because opacity: 1; when applied with a ID selector has priority over a class selector.

Replace this part:

elem.innerHTML = text[counter];

With:

$(elem)
    .fadeOut(400)
    .html(text[counter])
    .delay(400)
    .fadeIn(400);

本文标签: jqueryHow to add fade in and fade out when changing between texts in javascriptStack Overflow