javascript 如何将 CSS 应用于 document.write()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32176216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:57:22  来源:igfitidea点击:

How to apply CSS to document.write()?

javascripthtmlcssprinting

提问by ethanzh

I have a program that will use Javascript to 'print' a value to the screen using 'document.write()'. The value printed is an integer. I am looking to be able to use CSS to apply styling to this integer that is being printed out. Below is some truncated sample code of what I have tried doing, but it isn't working (the program just quits:

我有一个程序,它将使用 Javascript 使用“document.write()”将值“打印”到屏幕上。打印的值是一个整数。我希望能够使用 CSS 将样式应用于正在打印的这个整数。下面是我尝试做的一些截断的示例代码,但它不起作用(程序只是退出:

var number = 5 //just for an example
document.write('<p id="jstext"' + number + '</p>')

and this is the CSS code I'm using:

这是我正在使用的 CSS 代码:

#jstext {
    text-align: center;
    font-size: 90px;
}

Thanks

谢谢

回答by Praveen Kumar Purushothaman

That's wrong. See the correction:

那是错误的。看更正:

var number = 5; //just for an example
//------------^ // Not sure but ; is a must in some places.
document.write('<p id="jstext">' + number + '</p>')
//----------------------------^

You forgot a closing >here.

你忘了>在这里关闭。

Working snippet below:

下面的工作片段:

#jstext {
  text-align: center;
  font-size: 90px;
}
<script>
var number = 5; //just for an example
//------------^ // Not sure but ; is a must in some places.
document.write('<p id="jstext">' + number + '</p>')
//----------------------------^
</script>



UPDATE: Do not use the previous method.

更新:不要使用以前的方法。

The above method is totally wrong. It will remove all the event handlers and totally damage the DOM. A better way is to use:

上面的方法是完全错误的。它将删除所有事件处理程序并完全损坏 DOM。更好的方法是使用:

document.body.appendChild(document.createElement('p'));
document.querySelector("body p:last-child").id = "jstext";
document.querySelector("#jstext").innerHTML = number;

Snippet

片段

#jstext {
  text-align: center;
  font-size: 90px;
}
<script>
var number = 5; //just for an example
//------------^ // Not sure but ; is a must in some places.
document.body.appendChild(document.createElement('p'));
document.querySelector("body p:last-child").id = "jstext";
document.querySelector("#jstext").innerHTML = number;
</script>