您好,我有这个HTML,如下所示,如何在JavaScript函数myFunction中继承H1样式的CSS。单击后,将选择默认的h1样式。谢谢。
<html>
<style type="text/css">
body {
color: purple;
font: normal 18px Verdana, Arial, sans-serif;
background-color: white }
h1 {
color: Red;
font: normal 20px Verdana, Arial, sans-serif;
background-color: white }
</style>
<body>
<p id="demo"><h1>Click here.</h1></p>
<button onclick="myFunction()">Check it</button>
<script type="text/javascript">
function myFunction()
{
document.writeln("<h1>", "Hello there", "</h1>");
}
</script>
</body>
</html>
最佳答案
如果在文档处于关闭状态(在DOM准备就绪后将处于关闭状态)时调用document.write
(和writeln
),则将首先调用document.open
,然后覆盖文档。
由于文档被覆盖,因此样式表被销毁。
因此解决方案是不使用document.writeln
。请改用标准DOM方法。如果您需要有关如何执行此操作的介绍,则W3C会托管web standards curriculum,其中包括有关遍历DOM以及创建和修改HTML的章节。
关于javascript - javascript函数中的<h1> </h1>属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15685798/