改变 HTML 元素的属性,语法:document.getElementById(id).attribute=新属性值
<!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaSAcript</title> </head> <body> <img id="image" src="Anta.jpg" width="160" height="120"> <script> function myFunction(){ document.getElementById("image").src="Peak.jpg"; } </script> <button onClick="myFunction()">点击这里</button> </body> </html>
改变 HTML 元素的内容,语法:document.getElementById(id).innerHTML=新的 HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <h1 id="header">旧标题</h1> <script> function myClick(){ var element=document.getElementById("header"); element.innerHTML="新标题"; } </script> <button onClick="myClick()">点击这里</button> </body> </html>
改变 HTML 元素的样式,语法:document.getElementById(id).style.property=新样式
<!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> <script> function myClick(){ document.getElementById("p2").style.color="blue"; document.getElementById("p2").style.fontFamily="Arial"; document.getElementById("p2").style.fontSize="larger"; } </script> <button onClick="myClick()">点击这里</button> </body> </html>