返回到:DOM 对象:HTML DOM Document 对象
定义与用法
body 属性用于设置或返回文档体。
如果是返回, 该属性返回当前文档的 <body> 元素。
如果是设置, 该属性会覆盖所有在 <body> 元素中的子元素, 并用新的内容来替换它。
提示: 与 document.documentElement 属性不同的是, document.body 属性返回 <body> 元素, document.documentElement 属性返回 <html> 元素。
浏览器支持:
主流浏览器都支持。
语法
返回 body 属性:
document.body设置 body 属性:
document.body = newContent属性
| 值 | 描述 |
|---|---|
| newContent | 指定 <body> 的新内容 |
技术细节
| DOM 版本: | Core Level 1 Document Object |
|---|---|
| 返回值: | Body 对象的引用,表示 <body> 元素 |
实例
修改当前文档的背景颜色:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程网(web176.com)</title>
</head>
<body>
<p>点击按钮修改当前文档的背景颜色。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction() {
document.body.style.backgroundColor = "yellow";
}
</script>
</body>
</html>获取当前文档的 HTML 你内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程网(web176.com)</title>
</head>
<body>
<p>点击按钮显示文档的 HTML 的内容。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.body.innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>修改当前文档的 HTML 内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程网(web176.com)</title>
</head>
<body>
<p>点击按钮修改文档的 HTML 的内容。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
document.body.innerHTML = "新的内容...";
}
</script>
</body>
</html>创建 <p> 元素,并将其添加在文档中:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程网(web176.com)</title>
</head>
<body>
<p>点击按钮创建 p 元素及其内容,并将其添加在文档中。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.createElement("P");
var t = document.createTextNode("这是新增的段落。");
x.appendChild(t);
document.body.appendChild(x);
}
</script>
</body>
</html>作者:terry,如若转载,请注明出处:https://www.web176.com/javascriptbook/domtips/4579.html
支付宝
微信