<head>
<title>轮播</title>
<style>
body{
background-color: rgba(119, 115, 110);
}
ul{
width: 800px;
height: 200px;
list-style: none;
padding: 0;
/* 盒子水平垂直居中 */
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
ul:hover{
cursor: pointer;
}
li{
position: absolute;
left: 0;
transition: .4s;
}
</style>
<script>
window.onload=function(){
// 1.获取url
var cur_ul=document.getElementById('Carousel');
// 2.创建一个数组
var arr=new Array();
// 3.创建一个定时器 间歇调用
var timer=setInterval(get_next,3000)
// 动态创建image li
for(i=1;i<=5;i++){
// 1.创建li img
var cur_li=document.createElement('li');
var cur_img=document.createElement('img');
// 2.设置src属性
cur_img.src='./image/'+i+'.jpg';
// 3.给图片设置宽高
cur_img.style.width='400px';
cur_img.style.height='200px';
// 4.把img追加到了li当中 然后把li追加到ul当中
cur_li.appendChild(cur_img);
cur_ul.appendChild(cur_li);
// 给ul绑定一个 鼠标一进来停止轮播事件
cur_ul.onmouseenter=function(){
// 清除定时器
clearInterval(timer);
}
// 鼠标离开继续轮播
cur_ul.onmouseleave=function(){
timer=setInterval(get_next,3000);
}
// 5把每个li标签添加到数组中
arr.push(cur_li);
}
// len是数组的下标
var len=arr.length-1;
// 3 4 5
// len-2是最左边 len-1 中间 len最右边
arr[len-2].style.left='0px'; //3
arr[len-1].style.left='200px'; //4
arr[len].style.left='400px'; //5
// 扩大1.3倍
arr[len-1].style.transform='scale(1.3)';
// 浮在两张图片
arr[len-1].style.zIndex=100;
// 封装向右轮播图函数
function get_next(){
// 分析:[1,2,3,4,5];
// [5,1,2,3,4];
// [4,5,1,2,3];
var last=arr[arr.length-1];
// 1.把最后一张图片拿出来
arr.pop();
// 2.把最后一张图片放到第一张
arr.unshift(last);
// 3.处理轮播,除了中间的样式的其他图片
for(i=0;i<arr.length;i++){
arr[i].style.transform='scale(1)';
arr[i].style.zIndex=i;
};
arr[len-2].style.left='0px';
arr[len-1].style.left='200px';
arr[len].style.left='400px';
arr[len-1].style.transform='scale(1.3)';
arr[len-1].style.zIndex=100;
}
// 封装向左轮播图函数
function get_pre(){
// 获取第一张
var first =arr[0];
// 把第一张图片取出来
arr.shift();
// 放到第一张
arr.push(first);
for(i=0;i<arr.length;i++){
arr[i].style.transform='scale(1)';
arr[i].style.zIndex=i;
};
arr[len-2].style.left='0px';
arr[len-1].style.left='200px';
arr[len].style.left='400px';
arr[len-1].style.transform='scale(1.3)';
arr[len-1].style.zIndex=100;
}
// 创建左箭头
var pre_img = document.createElement('img');
// 显示图片路径
pre_img.src='./image/preImg.png';
// 图片样式
pre_img.style.position='absolute';
pre_img.style.top=0;
pre_img.style.left=0;
pre_img.style.bottom=0;
pre_img.style.margin='auto';
pre_img.style.zIndex=101;
cur_ul.appendChild(pre_img);
// 创建一个右箭头
var nex_img = document.createElement('img');
// 显示图片路径
nex_img.src='./image/nexImg.png';
// 图片样式
nex_img.style.position='absolute';
nex_img.style.top=0;
nex_img.style.right=0;
nex_img.style.bottom=0;
nex_img.style.margin='auto';
nex_img.style.zIndex=101;
cur_ul.appendChild(nex_img);
// 给左右箭头绑定事件
pre_img.onclick=function(){
get_pre();
}
nex_img.onclick=function(){
get_next();
}
}
</script>
</head>
<body>
<ul id="Carousel"></ul>
</body>
</html>
最终实现效果: