1.DOM简介
当网页被加载时,浏览器会创建页面的文档对象模型,即DOM(Document Object Model)。
2.DOM操作HTML
2.1 改变HTML输出流
不要在文档加载完成之后使用document.write()。会覆盖该文档
2.2 寻找元素
通过id找到HTML元素
通过标签找到HTML元素
2.3 改变HTML内容
使用属性:innerHTML
2.4 改变HTML属性
使用属性:attribute
Object_HTML.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--修改-->
<p id="pid">Hello</p>
<button onclick="demo()">按钮</button>
<script>
function demo(){
var nv=document.getElementById("pid");
nv.innerHTML="World";
document.getElementsByName("p");//p如果相同,相同元素的第一个
}
</script>
<!--修改属性-->
<br />
<a id="aid" href="http://www.baidu.com">百度</a>
<button onclick="demobd()">跳转</button>
<script>
function demobd(){
document.getElementById("aid").href="index.html";
}
</script>
<br />
<img id="iid" src="img/294224.jpg" height="200" width="300"/>
<button onclick="demoimg()">切换</button>
<script>
function demoimg(){
document.getElementById("iid").src="img/308048.jpg";
}
</script>
</body>
</html>
3.DOM操作CSS
通过DOM对象改变CSS
语法:document.getElementById(id).style.property=new style
Object_CSS.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/Object_CSS.css" />
</head>
<body>
<div id="div" class="div">
hello
</div>
<button onclick="demo()">按钮</button>
<script>
function demo(){
document.getElementById("div").style.background="blue";
document.getElementById("div").style.color="white";
}
</script>
</body>
</html>
css/Object_CSS.css
.div{
background-color: blueviolet;
height: 200px;
width: 300px;
}
4.DOM EventListener
4.1 DOM EventListenter
方法:addEventListener()
removeEventListener()
4.2 addEventListener()
方法用于指定元素添加句柄
4.3 removeEventListener()
移除方法添加句柄
EventListener.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">按钮</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
alert("hello");
});
</script>
<button id="btnjb">句柄</button>
<script>
var x=document.getElementById("btnjb");
x.addEventListener("click",hello);
x.addEventListener("click",world);
x.removeEventListener("click",hello);
function hello(){
alert("hello");
}
function world(){
alert("world");
}
</script>
</body>
</html>

被折叠的 条评论
为什么被折叠?



