简体   繁体   English

JavaScript函数将HTML内容替换几秒钟,然后恢复原状。

[英]JavaScript function to replace HTML contents for a few seconds, then revert back.

I'm making a hangman game using JavaScript and need to hide some HTML for a few seconds to display an error message, and then revert back to the original HTML. 我正在使用JavaScript制作子手游戏,需要隐藏一些HTML几秒钟以显示错误消息,然后恢复为原始HTML。 I've tried using setTimeout(); 我试过使用setTimeout(); and setInterval(); 和setInterval(); but those seem to just wait a few seconds before displaying the error message. 但是那些似乎只是等待几秒钟,然后显示错误消息。

Here's the code for reference: 这是供参考的代码:

<div class="row text-center">
    <div id="alredGuess" class="col">
        <div>
            <span id="guessedLetters"></span> <br>
        </div>
        <div>Guesses left:<span id="guessesLeft">10</span></div>
        <div>Wins:<span id="wins">0</span></div>
        <div>Losses:<span id="losses">0</span></div>
</div>
</div>

JS: JS:

if (gameRunning === true && guessedLetterBank.indexOf(letter) === -1) {
        // run game logic
        guessedLetterBank.push(letter);

        // Check if letter is in picked word
        for (var i = 0; i < pickedWord.length; i++) {
            //convert to lower case
            if (pickedWord[i].toLowerCase() === letter.toLowerCase()) {
                //if match, swap placeholder
                pickedWordPlaceholderArr[i] = pickedWord[i];
            }
        }

        $placeholders.textContent = pickedWordPlaceholderArr.join("");
        checkIncorrect(letter);

    } else if (gameRunning === false) {
        $placeholders.textContent = "Press \"A\" To Begin!"
    } else {
        //alert("You've already guessed this letter.")
        function newAlert() {
            var hideDiv = document.getElementById("alredGuess");
            if (hideDiv.style.display = "block") {
                hideDiv.style.display = "none";
              }
            }
            hideDiv.textContent("You've already guessed this letter!");
            function showDiv() {
            var showDiv = document.getElementById("alredGuess");
            if (hideDiv.style.display = "none") {
                hideDiv.style.display = "block";
              }
             }
            }
           }
            setInterval(newAlert, 3000);
    }

Tip 1 秘诀1

Well, first of all i don't recommend using display: block|none to show or hide DOM elements. 好吧,首先,我不建议使用display: block|none显示或隐藏DOM元素。 Instead try using visibility: visible|hidden or better, toggle a css class name such as : .hidden . 而是尝试使用visibility: visible|hidden或更好,切换CSS类名称,例如: .hidden That's because when you set a DOM element's display to none, its width and height are gonna be set to zero, often causing an unwanted loss of space because the DOM node visually collapses. 这是因为当您将DOM元素的显示设置为无时,其宽度和高度将被设置为零,这通常会导致不必要的空间损失,因为DOM节点会在视觉上崩溃。 With the visibility property, for example, the element just disappears without loss of space. 例如,借助可见性属性,元素将消失而不会损失空间。

Tip 2 秘诀2

Error/status messages should always live within their own containers. 错误/状态消息应始终位于其自己的容器中。 Do not display messages in substitution of some content you need to revert back after. 不要显示消息来代替您需要还原后的某些内容。 It is always better to prepare an empty <div> , hide it by default with a generic .hidden CSS class and then remove this one as soon as you need to display the container. 总是最好准备一个空的<div> ,默认情况下使用通用的.hidden CSS类将其隐藏,然后在需要显示容器时立即将其删除。

Suggested solution 建议的解决方案

Now, in your case, i think you're using setInterval in the wrong way. 现在,就您而言,我认为您以错误的方式使用了setInterval You have to immediately show the alert message, then make it disappear after a few seconds. 您必须立即显示警报消息,然后使其在几秒钟后消失。 As suggested above, this should be done by toggling CSS classes, using different containers and using setTimeout in order to remove/add the CSS classes as soon as the interval is over. 如上所述,这应该通过切换CSS类,使用不同的容器并使用setTimeout ,以便在间隔结束后立即删除/添加CSS类。 Basically, the setTimeout restores everything to its original state. 基本上, setTimeout将所有内容还原到其原始状态。

So, given this HTML code: 因此,给出以下HTML代码:

<div id="alredGuess">This is the original text</div>
<div id="alertbox" class="hidden"></div>

and this CSS code: 和此CSS代码:

.hidden { visibility: hidden; }

try this: 尝试这个:

var alertTimeout = 1000; // Timeout in milliseconds.

function showAlertMessage() {

    // This is your original text container.
    var alredGuess = document.getElementById("alredGuess");

    // This is the new error message container named #alertbox
    var alertBox = document.getElementById("alertbox");

    // Now let's fill it with the specific error text (better using HTML here).
    alertBox.innerHTML = "You've already guessed this letter!";

    // Hide the original container by adding an .hidden css class.
    alredGuess.classList.add('hidden');

    // Show the error message container by removing its default .hidden css class.
    alertBox.classList.remove('hidden');

   // Then set up an interval: as it ends, revert everything to its original state.
    setTimeout(function() {
        alertBox.classList.add('hidden');
        alredGuess.classList.remove('hidden');
    }, alertTimeout);
}

// Call the function.
showAlertMessage();

Fiddle: https://jsfiddle.net/qyk4jspd/ 小提琴: https : //jsfiddle.net/qyk4jspd/

Hope this helps. 希望这可以帮助。

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

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