简体   繁体   English

制作<p>使用 JS 或 JQuery 一段时间后消失</p>

[英]Make <p> disappear after certain amount of time using JS or JQuery

I'm working on a project that requires me to show and hide text.我正在做一个需要我显示和隐藏文本的项目。 I want one verse to appear on the screen, disappear after x amount of time, and then new text appears.我希望一首诗出现在屏幕上,在 x 时间后消失,然后出现新的文本。 I'm pretty new to Javascript & JQuery so I'm not really sure how to make this work.我对 Javascript 和 JQuery 很陌生,所以我不太确定如何完成这项工作。 Below is the code I have so far:以下是我到目前为止的代码:

HTML HTML

<p class="mast__text js-spanize" id="verse1">
 Magnetic light in the blue-high haze
</p>

<p class="mast__text js-spanize" id="verse2">
 A magnifying glass upon my face
</p>

<p class="mast__text js-spanize" id="verse3">
 It's so hot I've been melting out here 
</p>

JS: JS:

$("#verse1").show();
setTimeout(function() { $("#verse1").hide(); }, 2000);

$("#verse2").show();
setTimeout(function() { $("#verse2").hide(); }, 2000);

$("#verse3").show();
setTimeout(function() { $("#verse3").hide(); }, 2000);

Both functions seem to be called at the same time which is making the text appear and disappear at the same time.这两个函数似乎同时被调用,这使得文本同时出现和消失。 I'm sure that there is an easy fix to this that I'm overlooking, but I've looked online and can't seem to figure this out.我确信我忽略了一个简单的解决方法,但我在网上查看过,似乎无法解决这个问题。

The issue is that the code assumes that the setTimeout function waits for the time to finish.问题是代码假定 setTimeout function 等待时间完成。 Instead, the code continues on, an makes note to run the code after a specified time.取而代之的是,代码继续运行,并记下在指定时间后运行代码。 To fix it, you simply need to nest the setTimeout functions:要修复它,您只需嵌套 setTimeout 函数:

$("#verse2").hide(); // So these aren't showing at the start
$("#verse3").hide();

$("#verse1").show();
setTimeout(function() {
    $("#verse1").hide();

    $("#verse2").show();
    setTimeout(function() {
        $("#verse2").hide();

        $("#verse3").show();
        setTimeout(function() { $("#verse3").hide(); }, 2000);
    }, 2000);

}, 2000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM