javaScript改变HTML

改变HTML输出流:

在JavaScript中,document.write() 可用于直接向HTML输出流写内容

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <script>
 6 document.write(Date());
 7 </script>
 8 
 9 </body>
10 </html>

不要再文档加载之后使用document.writr()  这会覆盖文档。

 

改变HTML内容

修改HTML内容最简单的方法时使用innerHTML属性

 1 <html>
 2 <body>
 3 
 4 <p id="p1">Hello World!</p>
 5 
 6 <script>
 7 document.getElementById("p1").innerHTML="New text!";
 8 </script>
 9 
10 </body>
11 </html>

改变HTML属性

本例改变了<img>元素的src属性

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <img id="image" src="smiley.gif">
 6 
 7 <script>
 8 document.getElementById("image").src="landscape.jpg";
 9 </script>
10 
11 </body>
12 </html>

改变HTML元素的样式

本例改变了id="id1" 的HTML元素的样式,当用户点击按钮时:

1 <h1 id="id1">My Heading 1</h1>
2 
3 <button type="button" onclick="document.getElementById('id1').style.color='red'">
4 点击这里
5 </button>

 

使元素可见或不可见:

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <p id="p1">这是一段文本。</p>
 6 
 7 <input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" />
 8 <input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" />
 9 
10 </body>
11 </html>

 

posted @ 2017-09-12 17:59  千彧  阅读(218)  评论(0编辑  收藏  举报