<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM编程-innerHTML和innerText操作div</title>
<style type="text/css">
/*通过id选择器设置div属性样式*/
#div1{
background-color: aquamarine; /* 背景色 */
border: 1px black solid; /* 边框:粗细1px 黑色 实线 */
width: 300px; /* 宽度 */
height: 300px; /* 高度 */
position: absolute; /* 绝对定位 */
top: 100px; /* 距离顶部100px */
left: 100px; /* 距离左侧100px */
}
</style>
</head>
<body bgcolor="antiquewhite">
<!--
innerHTML与innerText属性有什么区别:
相同点:
都是设置元素内部的内容
不同的:
innerHTML:会把后面的字符串当做一段HTML代码解释并执行
innerText:即使后面是一段HTML代码,也只是当做普通字符串看待
-->
<script type="text/javascript">
window.onload = function(){
document.getElementById("btn1").onclick = function(){
//document.getElementById("div1").innerHTML = "字符串";
document.getElementById("div1").innerHTML =
"<font color='red'>欢迎学习JavaScript</font>";
}
document.getElementById("btn2").onclick = function(){
document.getElementById("div1").innerText =
"<font color='red'>欢迎学习JavaScript</font>";
}
}
</script>
<input type="button" value="点击按钮设置div里面的内容使用innerHTML" id="btn1" />
<input type="button" value="点击按钮设置div里面的内容使用innerText" id="btn2" />
<div id="div1"></div>
</body>
</html>
DOM编程-innerHTML与innerText属性对比
于 2023-02-07 19:57:58 首次发布