目录
轮播图
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片轮播</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="main" id="main">
<!-- 图片轮播 -->
<div class="banner" id="banner">
<a href="">
<div class="banner-slide slide1 slide-active">
</div>
</a>
<a href="">
<div class="banner-slide slide2">
</div>
</a>
<a href="">
<div class="banner-slide slide3">
</div>
</a>
</div>
<!-- 上一张 下一张按钮 -->
<a href="javascript:void(0)" class="button prev" id="prev"></a>
<a href="javascript:void(0)" class="button next" id="next"></a>
<div class="dots" id="dots">
<span class="active"></span>
<span></span>
<span></span>
</div>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
css代码
*{
margin: 0;
padding:0;
}
ul{
list-style: none;
}
body{
font: "微软雅黑";
color: #14191e;
}
.main{
width:1200px;
height:460px;
margin:30px auto;
overflow: hidden;
position:relative;
}
.banner{
width:1200px;
height: 460px;
overflow: hidden;
position: relative;
}
.banner-slide{
width:1200px;
height:460px;
background-repeat: no-repeat;
position: absolute;
display:none;
}
.slide-active{
display: block;
}
.slide1{
background-image: url("../img/bg1.jpg");
}
.slide2{
background-image: url("../img/bg2.jpg");
}
.slide3{
background-image: url("../img/bg3.jpg");
}
.button{
position: absolute;
width:40px;
height: 80px;
left:244px;
top:50%;
margin-top:-40px;
background:url("../img/arrow.png") no-repeat center center;
}
.button:hover{
background-color: #333;
opacity: 0.8;
filter:alpha(opacity=80);
}
.prev{
transform: rotate(180deg);
}
.next{
left:auto;
right:0;
}
.dots{
position: absolute;
bottom:24px;
right:0px;
text-align: right;
padding-right: 24px;
line-height: 12px;
}
.dots span{
display: inline-block;
width:12px;
height:12px;
border-radius: 50%;
margin-left: 8px;
background-color: rgba(7,17,27,0.4);
cursor: pointer;
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8) inset;
}
.dots span.active{
box-shadow: 0 0 0 2px rgba(7, 17, 27, 0.4) inset;
background-color: #ffffff;
}
效果图
封装byId()方法
//封装一个代替getElementById()的方法
function byId(id){
return typeof(id)==="string"?document.getElementById(id):id;
}
图片自动轮播
function byId(id){
return typeof(id)==="string"?document.getElementById(id):id;
}
//全局变量
var index =0;
timer=null;
pics=byId("banner").getElementsByTagName("div");
len=pics.length;
function slideImg(){
var main = byId("main");
//滑过清除定时器,离开继续
main.onmouseover =function(){
//滑过清除定时器
}
main.onmouseout =function(){
timer = setInterval(function(){
index++;
if(index>=len){
index=0;
}
//切换图片
changeImg();
},2000);
}
}
//切换图片
function changeImg(){
//遍历banner下多有的div,将其隐藏
for(var i=0;i<len;i++){
pics[i].style.display = "none"
}
//根据index索引找到当前div,将其显示出来
pics[index].style.display="block";
}
slideImg();
图片自动轮播和停止
点击圆点切换图片
在slideImg()中加入:
按钮切换图片
轮播图代码
function byId(id){
return typeof(id)==="string"?document.getElementById(id):id;
}
//全局变量
var index =0;
timer = null;
pics = byId("banner").getElementsByTagName("di