前端的第十九天(DOM)
4.操作元素
<script>
var btns = document.getElementsByTagName('button');
for(var i=0 ; i<btns.length ;i++){
btns[i].onclick = function(){
for(var i=0 ; i<btns.length ;i++){
btns[i].style.backgroundColor = '';
}
this.style.backgroundColor = 'pink';
}
}
</script>
<style>
body {
background-image: url("");
}
ul{
margin: 100px auto;
}
li,img {
width: 200px;
height: 200px;
display: inline-block;
}
</style>
</head>
<body>
<ul>
<li> <img src="./images/1.jpg" alt=""> </li>
<li> <img src="./images/2.jpg" alt=""> </li>
<li> <img src="./images/3.jpg" alt=""> </li>
<li> <img src="./images/4.jpg" alt=""> </li>
</ul>
<script>
var body = document.querySelector('body');
var imgs = document.querySelector('ul').querySelectorAll('img');
for(var i=0 ; i<imgs.length ; i++){
imgs[i].onclick = function(){
body.style.backgroundImage = 'url(' + this.src +')';
}
}
</script>
<div data-zdy="2"></div>
<div data-zdy="3"></div>
<div data-zdy="55"></div>
<div data-zdy="21"></div>
<div data-zdy="19"></div>
<div data-zdy="18"></div>
<script>
var divs = document.querySelectorAll('div');
for(var i=0 ; i<divs.length ; i++){
console.log(divs[i].getAttribute('data-zdy'));
divs[i].setAttribute('data-zdy','520caicai')
console.log(divs[i].getAttribute('data-zdy'));
}
</script>
5.节点操作
var nav = document.querySelector('.nav');
var lis = nav.children;
for (var i = 0; i < lis.length; i++) {
lis[i].onmouseover = function() {
this.children[1].style.display = 'block';
}
lis[i].onmouseout = function() {
this.children[1].style.display = 'none';
}
}
function getNextElementSibling(element) {
var el = element;
while (el = el.nextSibling) {
if (el.nodeType === 1) {
return el;
}
}
return null;
}
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
text-align: center;
line-height: 100px;
font-size: 20px;
color: aliceblue;
}
</style>
</head>
<body>
<div style="background-color: white;" class="father">
<div style="background-color: skyblue;" class="sc">生成盒子</div>
</div>
</body>
<script>
var father = document.querySelector('.father');
var sc = document.querySelector('.sc');
sc.onclick = function(){
var son = document.createElement('div');
father.insertBefore(son,father.children[0]);
}
</script>
内容详见下一篇文章: 点击跳转
|