HTML DOM innerHTML 属性
htmlweb developmentfront end technology更新于 2025/9/18 7:08:17
HTML DOM innerHTML 属性返回并允许我们修改元素的内部 HTML。内部 HTML 即内容。
语法
以下是语法 −
1. 返回 innerHTML
object.innerHTML
2. 设置内部 HTML
object.innerHTML=”value”
这里,"value"代表内容或嵌套的 HTML 元素。
示例
让我们看一个 innerHTML 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
}
.outer-box{
background-color:#347924;
width:200px;
height:200px;
padding:10px;
text-align:center;
font-weight:bold;
color:white;
margin:1rem auto;
}
.inner-box{
width:100px;
height:100px;
margin:3rem auto;
background-color:#8dce79;
}
.inner-circle{
width:100px;
height:100px;
border-radius:50%;
background-color:#8dce79;
margin:3rem auto;
}
</style>
</head>
<body>
<h1>innerHTML property Example</h1>
<div class="outer-box">
</div>
<button onclick="getsquare()">Get Square</button>
<button onclick="getcircle()">Get Circle</button>
<script>
function getsquare() {
var outerBox = document.querySelector('.outer-box');
outerBox.innerHTML ='<div class="inner-box">square</div>';
}
function getcircle() {
var outerBox = document.querySelector('.outer-box');
outerBox.innerHTML ='<div class="inner-circle">circle</div>';
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"获取正方形"按钮,在绿色正方形内显示正方形。

现在,点击"获取圆形"按钮,在绿色正方形内显示圆形。

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

