圖片輪播原理:
原理很簡單 就是將所有圖片平鋪在一行 然後在結合定時器 利用偏移量不斷的移動
代碼展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
#wrap {
overflow: hidden;
width: 600px;
height: 400px;
margin: 100px auto 0;
list-style: none;
position: relative;
}
img {
width: 600px;
height: 400px;
float: left;
}
#list {
position: absolute;
width: 4200px;
left: -600px;
height: 400px;
z-index: 10;
}
.arrow {
position: absolute;
width: 30px;
height: 50px;
font-size: 30px;
z-index: 90;
background-color: rgb(37, 34, 47);
color: white;
opacity: 0.3;
top: 200px;
cursor: pointer;
text-align: center;
}
.right {
position: absolute;
right: 0;
}
#buttons {
position: absolute;
z-index: 10;
bottom: 20px;
width: 100px;
height: 10px;
left: 250px;
}
#buttons span {
float: left;
margin-right: 5px;
width: 10px;
height: 10px;
border-radius: 50%;
background: #333;
cursor: pointer;
}
#buttons .on {
background-color: rgb(193, 23, 7);
}
</style>
</head>
<body>
<div id="wrap">
<div id="list">
<img src="img/5.png" alt="">
<img src="img/1.png" alt="">
<img src="img/2.png" alt="">
<img src="img/3.jpg" alt="">
<img src="img/4.png" alt="">
<img src="img/5.png" alt="">
<img src="img/1.png" alt="">
</div>
<div id="buttons">
<span class="on"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div class="arrow left" id="prev">
< </div>
<div class="arrow right" id="next">
> </div>
</div>
</div>
</body>
<script type="text/javascript">
var list = document.getElementById("list");
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var spans = document.getElementsByTagName("span");
var nexts;
var index = 1;
function play(setPx) {
var newLeft = list.offsetLeft - setPx;
list.style.left = newLeft + 'px';
if (newLeft < -3000) {
list.style.left = -600 + 'px';
}
if (newLeft > -600) {
list.style.left = -3000 + 'px';
}
}
function buttonShow() {
for (var i = 0; i < spans.length; i++) {
if (spans[i].className == "on") {
spans[i].className = "";
}
}
spans[index - 1].className = "on";
}
prev.onclick = function() {
index = index - 1;
if (index < 1) {
index = 5
}
play(-600)
buttonShow();
}
next.onclick = function() {
index = index + 1;
if (index > 5) {
index = 1
}
play(600)
buttonShow();
}
function clickshow() {
for (var i = 0; i < spans.length; i++) {
spans[i].ins = i;
spans[i].onclick = function() {
var newindex = this.ins + 1;
var setPX = -600 * (index - newindex);
console.log(setPX);
play(setPX)
index = newindex;
buttonShow();
}
}
}
clickshow();
function plays() {
nexts = setInterval(function() {
next.onclick();
}, 2000)
}
plays();
var wrap = document.getElementById("wrap")
function stop() {
clearInterval(nexts)
}
wrap.onmouseover = stop;
wrap.onmouseout = plays;
</script>
</html>