简体   繁体   English

有什么方法可以强制在 javascript 循环中重新绘制 DOM 元素?

[英]Is there any way to force repaint of DOM element inside javascript loop?

Here is a simplified example of a problem I am trying to solve.这是我试图解决的问题的简化示例。

I have a javascript loop and on each iteration, I ask for some input from the user and then want to display it in the browser during the the next iteration.我有一个 javascript 循环,在每次迭代中,我都会要求用户提供一些输入,然后希望在下一次迭代期间将其显示在浏览器中。 Currently it saves up all repaint operations to the end of the script and then processes them in a block.目前它将所有重绘操作保存到脚本的末尾,然后在一个块中处理它们。 Is there a way to force a refresh/repaint in the browser while the loop is in progress?有没有办法在循环进行时在浏览器中强制刷新/重绘?

Here's the code.这是代码。

<html>

  <head>
    <script>
      function mirror() {
        var userText = "Your text will go here";

        do {
          document.getElementById("target").innerHTML += userText + "<br>";
          userText = prompt("Enter your text, or click Cancel to finish");
        }
        while (userText !== null);
      }

    </script>
  </head>

  <body onload="mirror()">
    <p id="target"></p>
  </body>

</html>

The normal recommendation for browser repaint is to use window.setTimeout() however this is not working within the loop.浏览器重绘的正常建议是使用 window.setTimeout() 但这在循环中不起作用。

The synchronous blocking while is the problem - until the current Javascript stops running and yields to let the browser handle other stuff (like repainting), no repainting will occur.同步阻塞while是问题所在——直到当前的 Javascript 停止运行并让浏览器处理其他内容(如重绘),才会发生重绘。

You might add a slight asynchronous delay inside the loop - after setting the innerHTML , wait for 50ms before continuing:您可能会在循环内添加一个轻微的异步延迟 - 在设置innerHTML ,在继续之前等待 50 毫秒:

 const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); async function mirror() { var userText = "Your text will go here"; do { document.getElementById("target").innerHTML += userText + "<br>"; await delay(50); userText = prompt("Enter your text, or click Cancel to finish"); } while (userText !== null); } mirror();
 <p id="target"></p>

That said, this is somewhat of an X/Y problem.也就是说,这有点像 X/Y 问题。 It would be better to avoid prompt entirely - it blocks rendering (resulting in problems like these) and is somewhat user-unfriendly.最好完全避免prompt - 它会阻止渲染(导致此类问题)并且对用户不友好。 Consider creating a proper modal input instead, and then you can create the logic you need without blocking the browser.考虑创建一个适当的模态输入,然后您就可以在不阻塞浏览器的情况下创建您需要的逻辑。

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

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