82483564 2017-07-26
最近用到了图片轮播,经过测试后找到个不错的轮播代码。
推荐两个网址:http://www.jq22.com/jquery-info13688
www.jq22.com/jquery-info13688
在这里分享下:其实原理就是一系列的大小相等的图片平铺,利用CSS布局显示若干图片,其余隐藏。通过计算偏移量利用定时器实现自动播放,或通过手动点击事件切换图片,控制点击事件时的宽度变化
这里我写下手动点击轮播:
首先父容器container存放所有内容,子容器list存在图片
<div id="container">
<div id="list" style="left: -600px;">
<img src="img/5.jpg" alt="1" />
<img src="img/1.jpg" alt="1" />
<img src="img/2.jpg" alt="2" />
<img src="img/3.jpg" alt="3" />
<img src="img/4.jpg" alt="4" />
<img src="img/5.jpg" alt="5" />
<img src="img/1.jpg" alt="5" />
</div>
<a href="javascript:;" id="prev" class="arrow"><</a>
<a href="javascript:;" id="next" class="arrow">></a>
</div>CSS:
* {margin: 0;padding: 0;text-decoration: none;}
body {padding: 20px;}
#container {position: relative;width: 600px;height: 400px;
border: 3px solid #333;overflow: hidden;}
#list {position: absolute;z-index: 1;width: 4200px;height: 400px;}
#list img {float: left;width: 600px;height: 400px;}
#buttons {position: absolute;left: 250px;bottom: 20px;z-index: 2;
height: 10px;width: 100px;}
#buttons span {float: left;margin-right: 5px;width: 10px;height: 10px;
border: 1px solid #fff;
border-radius: 50%;background: #333;cursor: pointer;}
#buttons .on {background: orangered; }
.arrow {
position: absolute;
top: 180px;
z-index: 2;
display: none;
width: 40px;
height: 40px;
font-size: 36px;
font-weight: bold;
line-height: 39px;
text-align: center;
color: #fff;
background-color: RGBA(0, 0, 0, .3);
cursor: pointer;}
.arrow:hover {
background-color: RGBA(0, 0, 0, .7); }
#container:hover .arrow {
display: block;}
#prev {
left: 20px;}
#next {
right: 20px;}window.onload = function() {
var list = document.getElementById('list');
var prev = document.getElementById('prev');
var next = document.getElementById('next');
function animate(offset) {
//获取的是style.left,是相对左边获取距离,所以第一张图后style.left都为负值,
//且style.left获取的是字符串,需要用parseInt()取整转化为数字。
var newLeft = parseInt(list.style.left) + offset;
list.style.left = newLeft + 'px';
}
prev.onclick = function() {
animate(600);
}
next.onclick = function() {
animate(-600);
}
} 我们利用偏移量left来获取图片,当看到left值小于3600时,因为没有第8张图片就出现空白,所以这里我们需要对偏移量做一个判断。
在animate函数里加上一段:
if(newLeft<-3000){
list.style.left = -600 + 'px';
}
if(newLeft>-600){
list.style.left = -3000 + 'px';
}解释:这里控制当翻到最后一张时,从头开始。也可以设置下距离,让其到最后一张时无法往下翻页