JS实现轮播图效果
一、用JS实现轮播图,简单分为五大步,具体看代码块注释
1.自动播放
2.鼠标进入停止播放
3.鼠标离开继续播放
4.点豆豆跳转到对应图片
5.给图片添加超链接
二、示例图
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简单的轮播图</title>
<style type="text/css">
body{
margin:0;
padding:0;
}
#box{
width:500px;
height:300px;
position:relative;
top:150px;
left:400px;
/*border:1px solid red;*/
}
#ulId{
list-style:none;
position:absolute;
right:15px;
bottom:10px;
z-index:3;
}
#ulId li{
width:10px;
height:10px;
border-radius:50%;
background:greenyellow;
margin:0 5px;
float:left;
z-index:3;
}
#ulId li:nth-child(1){
background:green;
}
#box img{
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
z-index:1;
}
#box img:nth-child(1){
z-index:2;
}
</style>
</head>
<body>
<div id="box">
<img src="img/1.jpg"/>
<img src="img/2.jpg"/>
<img src="img/3.png"/>
<img src="img/4.jpg"/>
<img src="img/5.jpg"/>
<img src="img/6.jpg"/>
<img src="img/7.jpg"/>
<img src="img/8.jpg"/>
<img src="img/9.jpg"/>
<ul id="ulId">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
<script type="text/javascript">
function $(str){
if(str.startsWith("#")){
return document.getElementById(str.substring(1));
}else if(str.startsWith(".")){
return document.getElementsByClassName(str.substring(1));
}else{
return document.getElementsByTagName(str);
}
}
//1.自动播放
let currIndex=0;
let myTime;
function autoPlay(){
//给所有li添加自定义属性
let liDoms=$("li");
for(let i=0;i<liDoms.length;i++){
liDoms[i].setAttribute("index",i);
}
//一、数据处理
myTime=setInterval(()=>{
//1.改变数据
currIndex++;
//2.边界处理
if(currIndex>=9){
currIndex=0;
}
//二、改变样式
//1.改图片
//让所有img的zIndex为1
for(let i=0;i<$("img").length;i++){
$("img")[i].style.zIndex=1;
}
//让当前img的zIndex为2
$("img")[currIndex].style.zIndex=2;
//2.改豆豆
//让所有li的background为greenyellow
let liDoms=$("#ulId").children;
for(let i=0;i<liDoms.length;i++){
liDoms[i].style.background="greenyellow";
}
//让当前li的background为green
liDoms[currIndex].style.background="green";
},1000);
}
//2.停止播放
function stopPlay(){
window.clearInterval(myTime);
}
//3.继续播放
//4.点豆豆改变图片
function goImg(index){
currIndex=index;
if(currIndex<0 || currIndex>9){
currIndex=0;
}
//二、改变样式
//1.改图片
//让所有img的zIndex为1
for(let i=0;i<$("img").length;i++){
$("img")[i].style.zIndex=1;
}
//让当前img的zIndex为2
$("img")[currIndex].style.zIndex=2;
//2.改豆豆
//让所有li的background为greenyellow
let liDoms=$("#ulId").children;
for(let i=0;i<liDoms.length;i++){
liDoms[i].style.background="greenyellow";
}
//让当前li的background为green
liDoms[currIndex].style.background="green";
}
//5.超链接
window.function(){
//1.自动播放
autoPlay();
//2.停止播放
$("#box").onmouseover=function(){
stopPlay();
}
//3.继续播放
$("#box").onmouseout=function(){
autoPlay();
}
//4.点豆豆改变图片
let liDoms=$("#ulId").children;
for(let i=0;i<liDoms.length;i++){
liDoms[i].onclick=function(){
goImg(this.getAttribute("index"));
}
}
}
</script>
还没有评论,来说两句吧...