<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Js简单轮播图</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
/* 创建相框,宽度与图片的大小一致。padding有5px的空隙 */
#mainBox {
width: 730px;
height: 454px;
padding: 5px;
border: 1px solid #333;
margin: 100px auto;
}
/*设置显示内容的宽高与图片的一致。子元素超出部分使用 overflow:hidden 属性进行隐藏*/
#innerBox {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
ul {
width: 1000%;
/* 设置为1000%使得所有li图片可以在同一排上 */
list-style: none;
position: absolute;
}
li {
float: left;
}
#index {
bottom: 0;
right: 0;
position: absolute;
margin-bottom: 15px;
margin-right: 10px;
}
span {
background-color: #fff;
padding: 0 3px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="mainBox">
<div id="innerBox">
<ul >
<li><a href="#"><img src="images/1.jpg" alt=""></a></li>
<li><a href="#"><img src="images/2.jpg" alt=""></a></li>
<li><a href="#"><img src="images/3.jpg" alt=""></a></li>
<li><a href="#"><img src="images/4.jpg" alt=""></a></li>
<li><a href="#"><img src="images/5.jpg" alt=""></a></li>
<li><a href="#"><img src="images/6.jpg" alt=""></a></li>
</ul>
<div id="index">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
</div>
</div>
</div>
<script type="text/javascript">
function spanOver() {
this.style.backgroundColor = "green";
// var moveImg = this.inNum; //自定inNum属性,不可以直接通过this.inNum的方式获取属性
var moveImg = this.getAttribute("inNum"); //使用setAttribute设置自定义属性,必须使用getAttribute获取属性
var imgObj = document.getElementById("innerBox").firstElementChild;
moveElement(imgObj, 10, moveImg *(-730));
// console.log();
// imgObj.style.left = moveImg * (-730) + "px";
}
function spanOut() {
this.style.backgroundColor = "";
}
function setImg() {
var spanObj = document.getElementById("index").children;
for (var i = 0; i < spanObj.length; i++) {
spanObj[i].setAttribute("inNum", i); //给每个属性添加标签
spanObj[i].onmouseover = spanOver; //为每个span添加鼠标进入函数
spanObj[i].onmouseout = spanOut; //为每个span添加鼠标离开事件
}
}
function moveElement(element, step, target) {
clearInterval(element.timeId);
var current = element.offsetLeft;
element.timeId = setInterval(function() {
//获取当前对象的位置
// console.log(current);
//确定是进行左移还是右移,确定step的方向。当target>current的时候,需要setp 为正。当target< current,setp为负
var mvstep = target - current>0 ? step : -step;
console.log(target - current);
console.log(step);
//进行移动的距离Math.abs(target-current)
if (Math.abs(target - current) > 0) {
Math.abs(target - current) > Math.abs(mvstep) ? current += mvstep : current += (target - current);
// console.log(current);
// console.log(element.offsetLeft);
} else if (Math.abs(target - current) == 0) {
clearInterval(element.timeId);
}element.style.left = current+"px";
}, 20);
}
setImg();
// var getObj = document.getElementById("mainBox");
</script>
</body>
</html>
来源:CSDN
作者:細雨沐風
链接:https://blog.csdn.net/qq_34343637/article/details/82423063