通过 HTML DOM,JavaScript 能够访问 HTML 文档中的每个元素。
改变元素内容的最简单的方法是使用 innerHTML 属性。
下面的例子更改 <p> 元素的 HTML 内容:
<html> |
<body> |
<p id="p1">Hello World!</p> |
<script> |
document.getElementById("p1").innerHTML="New text!"; |
</script> |
</body> |
</html> |
通过 HTML DOM,您能够访问 HTML 对象的样式对象。
下面的例子更改段落的 HTML 样式:
<html> |
<body> |
<p id="p2">Hello world!</p> |
<script> |
document.getElementById("p2").style.color="blue"; |
</script> |
</body> |
</html> |
HTML DOM 允许您在事件发生时执行代码。
当 HTML 元素"有事情发生"时,浏览器就会生成事件:
你可以在下一章学习更多有关事件的内容。
下面两个例子在按钮被点击时改变 <body> 元素的背景色:
<html> |
<body> |
<input type="button" onclick="document.body.style.backgroundColor='lavender';" |
value="Change background color" /> |
</body> |
</html> |
<html> |
<body> |
<script> |
function ChangeBackground() |
{ |
document.body.style.backgroundColor="lavender"; |
} |
</script> |
<input type="button" onclick="ChangeBackground()" |
value="Change background color" /> |
</body> |
</html> |
<html> |
<body> |
<p id="p1">Hello world!</p> |
<script> |
function ChangeText() |
{ |
document.getElementById("p1").innerHTML="New text!"; |
} |
</script> |
<input type="button" onclick="ChangeText()" value="Change text"> |
</body> |
</html> |