document.write是否会删除CSS样式?

3

我想运行脚本而不删除CSS样式。

例如,当随机数字显示时,我仍希望背景保持蓝色。

function myFunc() {
  document.write(Math.floor(Math.random() * 999));
}
body {
  background-color: blue;
}
<button onclick="myFunc()">Get random num</button>


3
是的,如果像那样使用document.write(),它会清除整个文档。这是不使用它的主要原因。添加一个输出元素,如<pre id="output"></pre>,然后使用document.getElementById('output').innerText = x;代替。 - user5734311
4个回答

0

那不是一个好的做法

你可以尝试这个

<!DOCTYPE html>
<html lang="">
<head>
 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test</title>
  <style>
    body{
  background-color: blue;
}
  </style>
</head>
<body>
  <p id="text"> </p>
  <button onclick="myFunc()">Get random num</button>
  <script>

     function myFunc(){
document.getElementById("text").innerHTML=( Math.floor(Math.random()*999));
}
  </script>
</body>
</html>


既然你谈到了良好的实践(你是对的,document.write不是良好的实践),如果你不添加任何标记,像在你的情况下一样,使用.innerText而不是.innerHTML更好。顺便说一句,你的颜色选择是无法阅读的。如何使用“background-color: wheat;”? - Stephen P

0

是的,确实如此。这是因为document.write()正在覆盖文档中可能存在的所有stylelink元素。 document.write()完全覆盖文档中的所有内容

示例:

function doIt() {
  document.write('text')
  
  doSomethingElse() // Will not get executed since the script tags have been removed
}
<button onclick='doIt()'>Use document.write</button>


0
将值放入另一个元素中,而不是创建新文档。
尝试:
let s = document.createElement("span");
s.innerHtml = Math.floor(Math.random()*999);
body.appendChild(s);

编辑: 我没有看到@Chris G回答了你的问题,但这里有一个稍微不同的方法,为每个随机生成新元素,而不是替换它。我猜他的答案更适合你。


0

是的,一旦您点击按钮,您的HTML代码将更改为:

<html><head></head><body>934</body></html>

它也会移除样式。

根据链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接