练习目标
轮播图,鼠标移入轮播停止,移出继续轮播,点击小圆点自动跳转相应图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
.box {
width: 600px;
height: 400px;
margin: 50px auto;
border: 2px solid teal;
position: relative;
overflow: hidden;
}
.box ul {
width: 2400px;
position: absolute;
left: 0px;
}
.box li {
float: left;
}
.box p {
position: absolute;
bottom: 10px;
width: 100%;
text-align: center;
}
.box p span {
display: inline-block;
width: 15px;
height: 15px;
background: #000;
border-radius: 50%;
margin-right: 5px;
}
.box p .active {
background: teal;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li><img src="./image/t1.png" alt=""></li>
<li><img src="./image/t2.png" alt=""></li>
<li><img src="./image/t3.png" alt=""></li>
<li><img src="./image/t4.png" alt=""></li>
</ul>
<p><span class='active'></span><span></span><span></span><span></span></p>
</div>
<script src="./js/myPackage.js"></script>
<script>
var oSpan = document.getElementsByTagName("span");
var oBox = document.getElementsByTagName("div")[0];
var oUl = oBox.getElementsByTagName("ul")[0];
var n = 0;
var over = setInterval(auto, 1000);
function auto() {
n++;
if (-600 * n == -2400) {
n = -1;
}
running(oUl, "left", 30, -600 * n);
for (i = 0; i < oSpan.length; i++) {
oSpan[i].className = "";
}
oSpan[n].className = "active";
}
oUl.onmouseover = function () {
clearInterval(over);
}
oUl.onmouseout = function () {
clearInterval(over);
over = setInterval(auto, 1000);
}
for (b = 0; b < oSpan.length; b++) {
oSpan[b].index = b;
oSpan[b].onclick = function () {
clearInterval(over);
oUl.style.left = (this.index) * (-600) + "px";
for (i = 0; i < oSpan.length; i++) {
oSpan[i].className = "";
}
this.className = "active";
over = setInterval(auto, 1000);
}
}
</script>
</body>
</html>
js代码
/*
*作用:获取元素的样式
*@parm {object} elem:标签
*@parm {string} attr:属性
*/
function getStyle(elem,arr){//标签:elem 属性:attribute
if(window.getComputedStyle){
//标准
var value= getComputedStyle(elem)[arr];
}else{
//IE
var value=elem.currentStyle[arr];
}
return value
}
/*
*作用:运动元素
*@parm {object} elem:标签
*@parm {string} attr:属性
*@parm {number} step:步长
*@parm {number} target:目标值
*/
function running(elem, attr, step, target) { //运动元素elem,属性attr,步长step,目标值target
step = parseInt(getStyle(elem, attr)) < target ? step : -step;
clearInterval(elem.out);
elem.out = setInterval(function () {
var n = parseInt(getStyle(elem, attr)) + step;
if ((n <= target && step) < 0||(n >= target && step > 0)) {
n = target;
clearInterval(elem.out);
}
elem.style.left = n + "px";
}, 30);
}
``