HTML DOM write() 和 writeln()的不同实例
2025-04-24
17
参考资料
HTML DOM write() 和 writeln() 方法
基本介绍
document.write()
和 document.writeln()
都是 JavaScript 中用于向 HTML 文档写入内容的方法。
主要区别
方法 | 描述 | 是否添加换行符 |
---|---|---|
write() | 向文档写入内容 | 否 |
writeln() | 向文档写入内容并在末尾添加换行符(\n ) | 是 |
标签和用法
这两个方法都属于 document
对象的方法,语法如下:
document.write(content); document.writeln(content);
功能
动态生成 HTML 内容
在页面加载过程中插入内容
可以包含 HTML 标签
实例
基本使用
<script> document.write("<h1>Hello World!</h1>"); document.writeln("<p>This is a paragraph.</p>"); document.write("<p>Another paragraph.</p>"); </script>
带 CSS 扩展的实例
<script> document.write('<div style="color: blue; font-size: 20px;">Styled content</div>'); document.writeln('<p style="background-color: #f0f0f0; padding: 10px;">Styled paragraph</p>'); </script>
使用外部样式
<style> .highlight { background-color: yellow; font-weight: bold; } </style> <script> document.writeln('<span class="highlight">Highlighted text</span>'); document.write('<div class="highlight">Another highlighted element</div>'); </script>
注意事项
如果在页面加载完成后调用这些方法,会覆盖整个文档
writeln()
的换行符只在<pre>
标签中可见现代开发中推荐使用 DOM 操作方法(如
createElement
、appendChild
)替代这些方法
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。