<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<ul id="list">
<li>6</li>
<li>7</li>
<li>8</li>
<li>8</li>
<li>1</li>
</ul>
<script type="text/javascript">
// DOM document object model 文档对象模型
// 提供了获取dom节点的方法
// document.getElementById();
// document.getElmentsByTagName();
// DOM操作:节点操作
var oList=document.getElementById('list');
// 子节点第一个和最后一个
oList.firstElementChild.style.color='red';
oList.lastElementChild.style.background = 'blue';
// 子节点下一个节点
oList.firstElementChild.nextElementSibling.style.background = '#fc3';
// 子节点上一个节点
oList.lastElementChild.previousElementSibling.style.background = 'green';
for(var i=0;i<oList.children.length;i++){
oList.children[i].onclick=function(){
alert(this.innerHTML);
}
}
</script>
</body>
</html>
parentNode父节点 和offsetParent(有定位的父节点)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box{
position: absolute;
}
</style>
</head>
<body>
<div id="box">
666
<ul>
<li>111</li>
<li>222</li>
</ul>
</div>
<script type="text/javascript">
var oLi= document.getElementsByTagName('li')[0];
oLi.onclick=function(){
console.log(this.parentNode.innerHTML);
console.log(this.offsetParent.innerHTML);
}
</script>
</body>
</html>
offsetLeft和offsetRight当前元素到定位父级的距离
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
tyle type="text/css">
#box {
border: #000000 1px solid;
width: 500px;
height: 500px;
position: relative;
margin: 0 auto;
}
#div1 {
width: 50px;
height: 50px;
position: absolute;
left: 50px;
top: 50px;
background: #0000FF;
border: #000000 1px solid;
}
</style>
</head>
<body>
<div id="box">
<div id="div1">
425424
</div>
</div>
<script type="text/javascript">
document.getElementById('div1').onclick = function() {
console.log(this.offsetLeft);
console.log(this.offsetTop);
}
</script>
</body>
</html>
元素创建
document.createElement('li');
追加子节点
appendchild();
onsubmit提交onreset重置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form" action="https://www.baidu.com" method="">
<input type="text" name="username">
<button>提交</button>
<button type="reset">重置</button>
<!-- <button type="button" name="btn">提交</button> -->
</form>
<script type="text/javascript">
var oForm = document.getElementById('form');
// oForm.btn.onclick = function(){
// alert(oForm.username.value);
// }
oForm.onsubmit = function(){
if(oForm.username.value != null && oForm.username.value != ''){
oForm.submit();
}
return false;
// if(oForm.username.value == null || oForm.username.value == ''){
// alert('对不起,不能提交');
// // return false 能够取消默认事件
// return false;
// }
}
oForm.onreset= function(){
alert("取消?");
return false;
}
</script>
</body>
</html>
网友评论