<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>淡入淡出</title>
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
body {
background: black;
}
div {
width: 200px;
height: 100px;
margin: 50px auto;
border: 2px solid red;
position: relative;
}
ul {
width: 200px;
height: 100px;
}
li {
float: left;
width: 200px;
height: 100px;
cursor: pointer;
opacity: 0;
position: absolute;
top: 0px;
left: 0px;
transition: all 1.8s;
}
.current {
opacity: 1;
}
li:nth-of-type(1) {
background: lime;
}
li:nth-of-type(2) {
background: pink;
}
li:nth-of-type(3) {
background: blue;
}
li:nth-of-type(4) {
background: orange;
}
li:nth-of-type(5) {
background: yellow;
}
</style>
</head>
<body>
<div>
<ul id="box">
<li class="current">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<script>
var uBox = document.getElementById('box');
var list = uBox.children;//uBox的所有子级
var num = -1;
var timer;
function move() {
clearInterval(timer);
timer = setInterval(function () {
num++;
if (num >= list.length) {
num = 0;
}
for (var i = 0; i < list.length; i++) {
list[i].setAttribute('class', '');
}
list[num].setAttribute('class', 'current');
}, 2000);
}
move();
for (var i = 0; i < list.length; i++) {
list[i].onmouseenter = function () {
clearInterval(timer);
}
}
uBox.onmouseleave = function () {
move();
}
</script>
</body>
</html>
a.children
选择a的所有子级,得到的是一个数组,不能直接进行控制,即使只有一个也不可以。
淡入淡出原理:
用类名控制li的不透明度(opacity),并给所有li添加过渡(transition)