我想运行脚本而不删除CSS样式。
例如,当随机数字显示时,我仍希望背景保持蓝色。
function myFunc() {
document.write(Math.floor(Math.random() * 999));
}
body {
background-color: blue;
}
<button onclick="myFunc()">Get random num</button>
我想运行脚本而不删除CSS样式。
例如,当随机数字显示时,我仍希望背景保持蓝色。
function myFunc() {
document.write(Math.floor(Math.random() * 999));
}
body {
background-color: blue;
}
<button onclick="myFunc()">Get random num</button>
那不是一个好的做法
你可以尝试这个
<!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()
正在覆盖文档中可能存在的所有style
和link
元素。 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>
let s = document.createElement("span");
s.innerHtml = Math.floor(Math.random()*999);
body.appendChild(s);
编辑: 我没有看到@Chris G回答了你的问题,但这里有一个稍微不同的方法,为每个随机生成新元素,而不是替换它。我猜他的答案更适合你。
<pre id="output"></pre>
,然后使用document.getElementById('output').innerText = x;
代替。 - user5734311