一、DOM简介
1.HTML DOM:当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)
->Element:<head>->Element:<title>->Text:"My title"
document->Root element:<html>->
->Element:<body>...
2.DOM操作HTML:JavaScript能够改变页面中的所有HTML元素。
JavaScript能够改变页面中的所有HTML属性。
JavaScript能够改变页面中的所有CSS样式。
JavaScript能够对页面中的所有事件作出反应。
二、DOM操作HTML
1.改变HTML输出流:注意,不要在文档加载完成之后使用document.write()。这会覆盖文档
2.寻找元素:通过id找到HTML元素
通过标签名找到HTML元素
3.改变HTML内容:使用属性:innerHTML
4.改变HTML属性:使用属性:attribute
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<title></title>
</head>
<body>
<a id=
"aid"
href=
"http://www.baidu.com"
>链接</a>
<button onclick=
"demo()"
>按钮</button>
<script>
function
demo(){
document.getElementById(
"aid"
).href=
"http://www.51cto.com"
;
}
</script>
</body>
</html>
|
三、DOM操作CSS
1.通过DOM对象改变CSS。
语法:document.getElementById(id).style.property=new style
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<title></title>
<link rel=
"stylesheet"
type=
"text/css"
href=
"style.css"
/>
</head>
<body>
<div id=
"div"
class=
"div"
>
Hello
</div>
<button onclick=
"demo()"
>按钮</button>
<script>
function
demo(){
document.getElementById(
"div"
).style.background =
"blue"
;
}
</script>
</body>
</html>
|
四、DOM EventListener
1.DOM EventListener:
方法:addEventListener():
removeEventListener():
2.addEventListener():方法用于向指定元素添加事件句柄
3.removeEventListener():移除方法添加的事件句柄
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<title></title>
<link rel=
"stylesheet"
type=
"text/css"
href=
"style.css"
/>
</head>
<body>
<button id=
"btn"
>按钮</button>
<script>
var
x = document.getElementById(
"btn"
);
x.addEventListener(
"click"
,hello);
x.addEventListener(
"click"
,world);
x.removeEventListener(
"click"
,hello);
function
hello(){
alert(
"Hello"
);
}
function
world(){
alert(
"World"
);
}
</script>
</body>
</html>
|
本文转自yeleven 51CTO博客,原文链接:http://blog.51cto.com/11317783/1793085