原生JS轮播图
2019-07-20 本文已影响0人
Hello杨先生
<title>轮播图</title>
<style>
*{
padding: 0;
margin: 0;
}
#main{
width: 500px;
height: 300px;
position: relative;
margin: 20px auto;
}
#pic{
width: 100%;
height: 100%;
}
span{
position: absolute;
top: 150px;
left: 0;
width: 30px;
height: 30px;
line-height: 30px;
background: #ccc;
opacity: .4;
text-align: center;
cursor: pointer;
}
#right{
margin-left: 470px;
}
#picNav{
position: absolute;
bottom: 10px;
left: 50%;
overflow: hidden;
transform: translateX(-50%);
}
#picNav li{
list-style: none;
float: left;
width: 20px;
height: 20px;
text-align: center;
line-height: 20px;
background: #cccccc;
color: black;
}
#picNav .active{
background: orangered;
color: white;
}
</style>
<div id="main">
<img src="./images/p1.jpg" alt="" id="pic">
<span id="left"><</span>
<span id="right">></span>
<ul id="picNav">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<script>
var arr=['./images/p1.jpg','./images/p2.jpg','./images/p3.jpg','./images/p4.jpg']
var pic = document.getElementById("pic");
var picL = document.getElementById("left")
var picR = document.getElementById("right")
var picNav = document.getElementById("picNav")
var picNavList = picNav.getElementsByTagName("li")
var div = document.getElementById("main")
var index =0
function change() {
if(index == arr.length-1){
index =0
}else {
index++
}
pic.src = arr[index]
for (var i=0;i<picNavList.length;i++){
picNavList[i].className = ""
}
picNavList[index].className = "active"
}
// 实现自动播放
var t= setInterval(change,1000)
//鼠标放在图片上停止定时器
pic.onmouseover =function () {
clearInterval(t)
}
pic.onmouseleave=function () {
t=setInterval(change,1000)
}
//实现左右按钮功能
picL.onmouseover=function () {
clearInterval(t)
}
picL.onmouseleave=function () {
t=setInterval(change,1000)
}
//左键功能实现
picL.onclick =function(){
if(index==0){
index = arr.length-1
}else {
index--
}
// index==0?(index = arr.length-1) : index--
pic.src = arr[index]
for (var i=0;i<picNavList.length;i++){
picNavList[i].className = ""
}
picNavList[index].className = "active"
}
//右键功能实现
picR.onmouseover=function () {
clearInterval(t)
}
picR.onmouseleave=function () {
t=setInterval(change,1000)
}
picR.onclick =change;
//实现导航功能
// for(var j=0;j<picNavList.length;j++ ){
// picNavList[j].index = j
// picNavList[j].onmouseover =function () {
// for (var n=0;n<picNavList.length;n++){
// picNavList[n].className = ""
// }
// this.className = "active";
// pic.src= arr[this.index]
// }
// }
for(let j=0;j<picNavList.length;j++ ){
picNavList[j].onmouseover =function () {
for (var n=0;n<picNavList.length;n++){
picNavList[n].className = ""
}
this.className = "active";
index = j
pic.src= arr[j]
}
}
picNav.onmouseover =function () {
clearInterval(t)
}
picNav.onmouseleave=function () {
t=setInterval(change,1000)
}
</script>