HTML DOM document.write() 方法
2025-04-24
15
参考资料
HTML DOM document.write() 方法
基本介绍
document.write() 是 JavaScript 中用于向 HTML 文档输出内容的方法
可以直接写入 HTML 标签和文本内容
通常在页面加载过程中使用
语法
document.write(content);参数说明
content: 要写入文档的 HTML 内容(字符串)
基本用法示例
<script>
document.write("<h1>Hello World</h1>");
document.write("<p>This is a paragraph.</p>");
</script>动态内容示例
<script>
var name = "John";
document.write("<p>Welcome, " + name + "!</p>");
</script>结合CSS样式
<script>
document.write("<p style='color:blue;font-size:20px;'>Styled text</p>");
</script>使用CSS类
<style>
.highlight {
background-color: yellow;
padding: 5px;
}
</style>
<script>
document.write("<span class='highlight'>Highlighted text</span>");
</script>注意事项
如果在文档加载完成后调用,会覆盖整个文档
不推荐在现代网页开发中频繁使用
更适合用于简单的测试和演示
替代方法
现代开发推荐使用:
innerHTML
textContent
DOM 操作方法(createElement, appendChild等)
完整示例
<!DOCTYPE html>
<html>
<head>
<style>
.output {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<script>
document.write("<div class='output'>");
document.write("<h2>Document.write() Demo</h2>");
document.write("<p>Current date: " + new Date() + "</p>");
document.write("</div>");
</script>
</body>
</html>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-1636.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
