JavaScript - 单击按钮使功能正常运行

时间:2018-04-06 22:30:14

标签: javascript jquery html

这是对this question的跟进,对不起让他们彼此如此接近。

我试图在点击然后运行后续功能时按钮消失,但是在这里,点击按钮会显示message2的第一个字符,然后再次淡入;继续单击该按钮会使每个后续字符显示,直到没有剩余,并且无论我单击多少次,第二个按钮都不会出现。它应该工作,所以这里有什么问题?

编辑:不知何故让我想到添加timer2。现在效果更接近我想要的效果,但它并没有完全匹配原始对话功能的效果(这就是我想要的)。

我的代码:



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));

var message2 = `Wonderful! Now let's try summoning another button.`

function dialogue2(add2 = 1) {
  $("#button1").hide();
  var timer2 = setInterval(dialogue2,20);
  var len2 = $("#pid2").text().length + add2; // Get desired length
  $("#pid2").text(message2.substr(0, len2)); // Make the change
  if (len2 < message2.length) return; // Nothing more to do
  clearInterval(timer2); // All is shown, so stop the animation
  $("#button2").fadeIn(); // and fade in the button
}

// Hide the button on page load
$("#button1").hide();
$("#button2").hide();
$("#button3").hide();
&#13;
<!DOCTYPE=HTML>
<html>

<head>
  <title>Sandbox</title>
  <link rel="stylesheet" href="mainstyle.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
  <p id="pid"></p>
  <button id="button1" onclick="dialogue2(add2 = 1);">Ooh, here's one! Click to see what it does!</button>
  <p id="pid2"></p>
  <button id="button2">Speak of the devil, and he shall come!</button>
  <p id="pid3"></p>
  <button id="button3">Last time, I promise!</button>


</body>

</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案