【问题标题】:How to apply CSS to document.write()?如何将 CSS 应用于 document.write()?
【发布时间】:2015-08-24 07:03:20
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 行尾缺少的分号是错字吗?

标签: javascript html css printing


【解决方案1】:

错了。查看更正:

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

您在这里忘记了结束&gt;

下面的工作sn-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。更好的方法是使用:

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

片段

#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>

【讨论】:

  • 啊,谢谢!现在可以了。还有一个问题,这样做比使用 innerHTML 有什么好处?输出有什么不同吗?
  • 那么使用你的方法比使用innerHTML更好吗? :)
  • 视情况而定。两者都更好。
  • 我的理解是 document.write 会强制重新加载整个文档,因此出于性能原因,innerHTML 更可取。
  • @DylanYoung 这是更改代码的糟糕方式。我马上更新代码。
猜你喜欢
  • 1970-01-01
  • 2010-09-18
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多