如何将CSS应用于document.write()? [英] How to apply CSS to document.write()?
问题描述
我有一个程序,它将使用Javascript使用'document.write()'将值打印到屏幕上。打印的值是整数。我希望能够使用CSS将样式应用于正在打印的整数。下面是我尝试过的一些截断的示例代码,但它不起作用(程序刚退出:
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:
var number = 5 //just for an example
document.write('<p id="jstext"' + number + '</p>')
这是我正在使用的CSS代码:
and this is the CSS code I'm using:
#jstext {
text-align: center;
font-size: 90px;
}
谢谢
推荐答案
这是错误的。看到更正:
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>')
//----------------------------^
您忘了在此处关闭>
。
以下工作代码段:
#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>
更新:请勿使用上一个方法。
上面的方法是完全错误的。它将删除所有事件处理程序并完全破坏DOM。更好的方法是使用:
The above method is totally wrong. It will remove all the event handlers and totally damage the DOM. A better way is to use:
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>
这篇关于如何将CSS应用于document.write()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!