JS/JQuery隐藏元素,更改文本,显示元素

JS/JQuery hide element, change text, show element

本文关键字:元素 文本 显示 隐藏 JS JQuery      更新时间:2024-02-17

我正在努力实现以下体验:

  • 向下滑动要隐藏的文本
  • 将文本更改为存储在数组中的值(在文本从视图中完全隐藏之前,不要更改文本)
  • 向上滑动文本以显示

不断发生的是,在元素完全隐藏之前,文本正在发生变化。这是在页面加载时运行的函数。。。

var welcomeText = function() {
var welcome = ["Bienvenue.", "Willkommen.", "Benvenuto.", "Bienvenido.", "Welkom", "欢迎", "Fáilte.", "Nau mai", "Welcome."],
    title = $(".home-title"),
    counter = 0;
setInterval(function() {
    title.animate({"bottom":"-100%"},200);
    title.text(welcome[counter]);
    counter++;
    title.animate({"bottom":""},200);
    if(counter >= welcome.length) {
        counter = 0;
    }
}, 3000);
}

使用animate函数的完整参数。只有当animate函数结束时,函数内部的代码才会执行。

title.animate({"bottom":"-100%"},200,function() {
  title.text(welcome[counter]);
  counter++;
  title.animate({"bottom":""},200);
  if(counter >= welcome.length) {
    counter = 0;
  }
});

哇,我突然想到了答案!我不得不在修改文本时加上一个时间延迟。这是有效的解决方案。。。

var welcomeText = function() {
var welcome = ["Bienvenue.", "Willkommen.", "Benvenuto.", "Bienvenido.", "Welkom", "欢迎", "Fáilte.", "Nau mai", "Welcome."],
    title = $(".home-title"),
    counter = 0;
setInterval(function() {
    title.animate({"bottom":"-100%"},200);
    setTimeout(function() {
        title.text(welcome[counter]);
    }, 200);
    counter++;
    title.animate({"bottom":""},200);
    if(counter >= welcome.length) {
        counter = 0;
    }
}, 3000);}