本文实例为大家分享了html5轮播图的具体代码,供大家参考,具体内容如下
1.轮播图的布局:
*{
margin: 0;
padding: 0;
}
#outer{
width: 520px;
height: 333px;
margin: 50px auto;
background-color: greenyellow;
padding: 10px 0;
position: relative;
overflow: hidden;
}
#imgList{
list-style: none;
width: 2600px;
position: absolute;
left: 0px;
}
li{
float: left;
margin: 0 10px;
}
#nav{
position: absolute;
bottom: 20px;
left: 197px;
}
#nav a{
float: left;
width: 15px;
height: 15px;
background-color: red;
margin: 0 5px;
opacity: 0.5;
filter: alpha(opacity=50);
}
2.轮播图的逻辑:
*{
margin: 0;
padding: 0;
}
#outer{
width: 520px;
height: 333px;
margin: 50px auto;
background-color: greenyellow;
padding: 10px 0;
position: relative;
overflow: hidden;
}
#imgList{
list-style: none;
width: 2600px;
position: absolute;
left: 0px;
}
li{
float: left;
margin: 0 10px;
}
#nav{
position: absolute;
bottom: 20px;
left: 197px;
}
#nav a{
float: left;
width: 15px;
height: 15px;
background-color: red;
margin: 0 5px;
opacity: 0.5;
filter: alpha(opacity=50);
}
#nav a:hover{
background-color: black;
}
外部js代码:
function move(obj, attr, target, speed, callback) {
//关闭之前的定时器
clearInterval(obj.timer);
//判断向左移还是向右移
//0 --> 800 向右移
//起始位置 < 目标位置 则向右移动,速度为正
//800 --> 0 向左移
//起始位置 > 目标位置 则向左移动,速度为负
//获取元素的起始位置
var current = parseInt(getStyle(obj, attr));
if(current > target) {
//起始位置 > 目标位置 则向左移动,速度为负
speed = -speed;
}
//开启一个定时器,控制box1移动
obj.timer = setInterval(function() {
//获取box1的当前的left值
var oldValue = parseInt(getStyle(obj, attr));
//通过旧值来计算新值
var newValue = oldValue + speed;
//判断newValue是否大于800
if((speed > 0 && newValue > target) || (speed < 0 && newValue < target)) {
newValue = target;
}
//将box1的left值修改为新值
obj.style[attr] = newValue + "px";
//当box1移动到800px的位置时,停止移动
if(newValue == target) {
clearInterval(obj.timer);
//调用回调函数
callback && callback();
}
}, 30);
}
function getStyle(obj, name) {
//判断浏览器中是否含有getComputedStyle这个方法
if(window.getComputedStyle) {
//支持正常的浏览器
return getComputedStyle(obj, null)[name];
} else {
//只支持IE
return obj.currentStyle[name];
}
}
function addClass(obj, cn) {
//如果元素中有该class则不添加,没有才添加
if(!hasClass(obj, cn)) {
obj.className += " " + cn;
}
}
function hasClass(obj, cn) {
//创建正则表达式
var reg = new RegExp("\b" + cn + "\b");
//返回检查结果
return reg.test(obj.className);
}
function removeClass(obj, cn) {
//要删除一个class,就是将这个class替换为一个空串
//创建正则表达式
var reg = new RegExp("\b" + cn + "\b", "g");
//判断obj中是否含有这个class
if(reg.test(obj.className)) {
//将内容替换为空串
obj.className = obj.className.replace(reg, "");
}
}
function toggleClass(obj, cn) {
//检查obj中是否含有cn
if(hasClass(obj, cn)) {
//有该class,则删除
removeClass(obj, cn);
} else {
//没有该class,则添加
addClass(obj, cn);
}
}
注:图片自己找
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



