1. 程式人生 > >JS實現小圖放大輪播效果

JS實現小圖放大輪播效果

JS實現小圖放大輪播頁面效果入下(圖片為優行商旅頁面照片):

 實現效果:
圖片自動輪播,滑鼠移入停止,移出繼續輪播
點選下方小圖可以實現切換

步驟一:建立HTML佈局,具體如下:

 

<body>
    <div id="carousel" class="carousel" onmouseover="stop()" onmouseout="again()">
        <ul class="list" id="ulctrl">
            <li class="trans"><span
></span></li> <li><span></span></li> <li><span></span></li> <li><span></span></li> </ul> </div> </body>

 

 

 

  其中div為圖片輪播區域,li用於放置小圖

步驟二:CSS佈局

 

*{
            margin:0;
            padding:0;
        }
        ul{
            list-style: none;
            height:auto;
            position: absolute;
            top:95%;
            left:32%;
        }
        #carousel{
            width:100%;
            height:400px;
            background-image
: url(images/1.jpg); background-repeat: no-repeat; background-position: center; position: relative; } li{ float:left; margin-right: 20px; } span{ display: block; width:110px; height:41px; background-size: 110px 41px; border:none; } li:nth-child(1) span{ background-image: url(images/1.jpg); border:2px solid orange; } li:nth-child(2) span{ background-image: url(images/2.jpg); } li:nth-child(3) span{ background-image: url(images/3.jpg); } li:nth-child(4) span{ background-image: url(images/4.jpg); }

 

 

 

  通過定位使小圖顯示在下方,此時輪播區域顯示的為第一張圖片

步驟三:新增JS邏輯(其中該程式碼註釋中的圓點是指輪播圖下方小圖)

let cnt=1;//計數器
let ulctrl=document.getElementById("ulctrl");//圓點控制器
let lis=ulctrl.children;//圓點們
let linow=lis[0];//初始化當前圓點為第一個
let clock;//宣告計時器
var carousel=document.getElementById("carousel");//背景容器
for(let i=0;i<lis.length;i++){
    //給圓點繫結函式,點選改變圓點樣式和圖片
    lis[i].onclick=function (){
        cnt=i+1;
        carousel.style.backgroundImage="url(images/"+cnt+".jpg)";
        for(let li of lis){
             li.children[0].style.border = 'none';
        }
         this.children[0].style.border = '2px solid orange';
    }
}
//改變圓點樣式
function ctrl(){
    linow.children[0].style.border = 'none';
    linow=lis[cnt-1];
    linow.children[0].style.border = '2px solid orange';
}
//滑鼠覆蓋輪播圖,停止輪播
function stop(){
    clearInterval(clock);//清除計時器
}
//滑鼠離開輪播圖,繼續輪播
function again(){
    clock=setInterval(this.start, 2000);//建立計時器
}
//輪播函式
function start(){ 
    if(cnt==4){
        cnt=1;
    }else{
        cnt++;//更新計數器
    }
    carousel.style.backgroundImage="url(images/"+cnt+".jpg)";
    ctrl();//輪播狀態下改變圓點樣式
    }
(function move(){
    clock=setInterval(this.start, 2000);//建立計時器,2秒執行一次start函式
})();//自執行函式