28. JS DOM、点击事件
● 什么是加载事件onload
js代码执行时候,需要html&css的支持,就让html先执行(先进入内存),js代码后执行。
window.onload = function() {
}
onload在页面加载完之后执行
dom:用JS对html标签进行增删改查
● 元素节点获取:
● 文本节点获取:
<div>hello</div>
需要借助div元素节点再获得其内部的文本节点.
var dvnode = document.getElementsByTagName(‘div’)[0];
dvnode.firstChild; //(或调用lastChild)获得元素div内部的第
一个子节点对象,而不是自己这个节点
● 兄弟节点:
firstChild、lastChild:父节点获得第一个/最后一个子节点
nextSibling:获得下个兄弟节点
previousSibling:获得上个兄弟节点
childNodes:父节点获得内部全部的子节点信息
● 父节点
节点.parentNode;
● 属性值操作
1. 属性值操作
<input type=”text” name=”username” value=”tom” class=”orange” />
<a href=”http://www.baidu.com” addr=’beijing’ target=”_blank”>百度</a>
1.获取属性值
itnode.属性名称; //只能操作w3c规定的属性
itnode.getAttribute(属性名称); //规定的 和 自定义的都可以获取
2.设置属性值
itnode.属性名称 = 值; //只能操作w3c规定的属性
itnode.setAttribute(名称,值); //规定的 和 自定义的都可以设置
Field、Attribute、Property
● 节点创建和追加
节点创建
元素节点:document.createElement(tag标签名称);
文本节点:document.createTextNode(文本内容);
属性设置:node.setAttribute(名称,值);
节点追加:
父节点.appendChild(子节点);
父节点.insertBefore(newnode,oldnode); //newnode放到oldnode的前边
父节点.replaceChild(newnode,oldnode); //newnode替换到oldnode节点
● 节点删除
父节点.removeChild(子节点);
● 总结:
DOM操作
1. 元素、文本、属性、document节点获取
元素:getElementById()/getElementsByTagName()
文本:元素节点.firstChild/lastChild;
属性:元素节点.attributes;元素节点.attributes.属性名称;
document:元素节点.parentNode
2. 属性值操作
元素节点.属性名称;
元素节点.属性名称 = 值;
元素节点.getAttribute(属性名称);
元素节点.setAttribute(属性名称,值);
3. 节点创建、追加、复制、删除
创建:
元素-document.createElement(tag名称);
文本-document.createTextNode(文本内容);
元素节点.setAttribute();
追加:
父.appendChild(子);
父.replaceChild(new,old);
父.insertBefore(new,old);
删除:
父.removeChild(子)
● 事件
通过鼠标、键盘对页面所做的动作就是事件。
事件一旦发生需要有事件处理,该处理称为“事件驱动”,事件驱动通常由函数担任
onclick onmouseover onmouseout onkeyup onkeydown onblur onfocus onsubmit
1、是在标签内写onclick事件
2、是在JS写onlicke=function(){}函数
1) <input id="myButton" type="button" value="Press Me" οnclick="alert('thanks');" >
2) document.getElementById("myButton").onclick = function () {
alert('thanks');
}
● 例题:页面换肤
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
img {
width: 150px;
height: 130px;
}
.box{
/* 水平居中 */
text-align: center;
padding-top: 30px;
padding-bottom: 30px;
background-color: rgba(97,131,174,0.6);
}
body{
background-image: url(../img/1.jpg);
}
</style>
</head>
<!-- style="background-image: ;" -->
<body >
<div class="box">
<img src="../img/1.jpg" />
<img src="../img/2.jpg" />
<img src="../img/3.jpg" />
<img src="../img/4.jpg" />
<img src="../img/5.jpg" />
</div>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++) {
images[i].onclick = function() {
// this代表当前设置点击事件的对象
var imageSrc = this.src;
/* document.body.style.backgroundImage = 'url(../img/2.jpg)'; */
document.body.style.backgroundImage = 'url('+imageSrc+')';
}
}
}
</script>
</body>
</html>