如何将CSS应用于document.write()? [英] How to apply CSS to document.write()?

查看:58
本文介绍了如何将CSS应用于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆