首页 > 解决方案 > 在输出中编辑 JS 和 CSS

问题描述

这是一个有趣的技巧,如何在输出中查看和编辑 CSS 和 JS。例如,在输出中,您可以将颜色从 更改redblue

我的问题是为什么我不能以同样的方式更改脚本打印的文本?我的意思是,无论进行任何编辑,打印的文本仍然是foo而不是 eg bar。有没有办法让它工作?

<div></div>

<p>The contents of the <code>&lt;style&gt;</code> tag:</p>

<style contenteditable>
  div {
    color: red; /* You can change the color right in the **output**! */
  }

  script {
    background: lightgray;
  }

  style {
    background: aliceblue;
  }

  script, style {
    display: inline-block;
    font-family: monospace;
    white-space: pre-wrap;
    width: 100%;
  }
</style>

<p>The contents of the <code>&lt;script&gt;</code> tag:</p>

<script contenteditable>
  function timer() {
    /* You cannot do the same trick to replace foo with bar... */
    document.querySelector('div').append('foo ');
  }

  setInterval(timer, 1000);
</script>

标签: javascript

解决方案


因为script标签在插入 DOM 时只执行一次,所以您只是更改它的文本内容,不会重新评估script. 您可以模拟脚本评估,但script这里的标签没有多大意义:

<div></div>

<p>The contents of the <code>&lt;style&gt;</code> tag:</p>

<style contenteditable>
  div {
    color: red; /* You can change the color right in the **output**! */
  }

  script {
    background: lightgray;
  }

  style {
    background: aliceblue;
  }

  script, style {
    display: inline-block;
    font-family: monospace;
    white-space: pre-wrap;
    width: 100%;
  }
</style>

<p>The contents of the <code>&lt;script&gt;</code> tag:</p>

<script id="code" contenteditable>
  document.querySelector('div').append('foo ');
</script>

<script>setInterval(() => eval(code.textContent), 1000)</script>


推荐阅读