JavaScript – 完成函数后如何淡入隐藏的按钮元素?

我是JavaScript / HTML / CSS的新手,所以我不知道如何解决这个问题。

我要做的是编写一个脚本,在特定函数中显示一些文本,然后,当函数完成显示文本时,自动淡入HTML按钮或等效,而不必单击任何特定元素。 我想象按钮必须先插入并以某种方式隐藏,并且淡入是改变按钮可见性的问题。 这可能在Javascript中,还是有其他(可能更容易)的方法? 任何帮助将不胜感激。

这是我到目前为止的代码:

   Sandbox     

var a = 1; function dialogue(){ var message = "This message is (hopefully) a successful implementation of JS video game scrolling!

Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript!

Let's see if we can add some fade-in buttons, shall we?

(By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)"; if(a <= message.length) { var txt = message.substring(0,a); document.getElementById ("pid").innerHTML = txt; setTimeout("dialogue()",20); a++; document.onclick = function(){ a = message.length; }; } }; dialogue();

您可以在达到所需长度时显示按钮(您的代码中已经有相反的条件)。

也许还会改进一些事情:

  • 避免将字符串作为第一个参数传递给setTimeout :最佳做法是传递函数。

  • 避免在每次dialogue时分配一个点击处理程序; 你只需要定义一次。

  • 尽可能避免在函数内修改全局变量。

  • 使用HTML剪切字符串会使HTML无效,就像将剪辑剪切到一半时一样。 没错,浏览器可以处理未关闭的标签,但对于像 这样的实体来说会更成问题  。 最好使用纯文本(包括换行符)并将其分配给textContent属性(或text jQuery函数),同时使用white-space CSS属性以确保换行符这样呈现。 可以使用反引号(ES6)定义字符串,这样您就可以使用回车键来换行。

我也会在这里使用setInterval而不是setTimeout ,但这只是个人偏好:

 var message = `This message is (hopefully) a successful implementation of JS video game scrolling! Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript! Let's see if we can add some fade-in buttons, shall we? (By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)`; var timer = setInterval(dialogue, 20); function dialogue(add = 1){ // By default 1 character is made visible var len = $("#pid").text().length + add; // Get desired length $("#pid").text(message.substr(0, len)); // Make the change if (len < message.length) return; // Nothing more to do clearInterval(timer); // All is shown, so stop the animation $("#button1").fadeIn(); // and fade in the button }; // On click, pass the length of the message to the function $(document).click(dialogue.bind(null, message.length)); // Hide the button on page load $("#button1").hide(); 
 #pid { white-space: pre-wrap } 
  

如果要在完成编写文本后显示按钮,可以将此代码添加到if语句中

 else{ document.getElementById("button1").style.display = "block"; } 

这将在您完成写入时显示按钮,因为此语句不正确: a <= message.length

演示

 #button1{ display:none;} 
    Sandbox     

当然,这是可能的。 如果我找到你,你只需要在函数中添加一个else,并使按钮可见。 当然,如果您使用类,则可以轻松定义css淡入效果。

    Sandbox