1. 程式人生 > >JavaScript實現簡單的圖片輪播(通過點選左右焦點切換)

JavaScript實現簡單的圖片輪播(通過點選左右焦點切換)

最終實現效果圖

這裡寫圖片描述

程式碼塊

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        body, ul, ol, li, img {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        #box {
            width
: 490px
; height: 270px; padding: 5px; position: relative; border: 1px solid #ccc; margin: 100px auto 0; }
.ad { width: 490px; height: 270px; overflow: hidden; position: relative; }
#box img { width: 490px; } .ad ol { position: absolute; right: 10px; bottom: 10px; } .ad ol li { width: 20px; height: 20px; line-height: 20px; border: 1px solid #ccc; text-align
: center
; background: #fff; float: left; margin-right: 10px; cursor: pointer; _display: inline; }
.ad ol li.current { background: yellow; } .ad ul li { float: left; } .ad ul { position: absolute; top: 0; width: 2940px; } .ad ul li.current { display: block; } #arr { display: none; } #arr span { width: 40px; height: 40px; position: absolute; left: 5px; top: 50%; margin-top: -20px; background: #000; cursor: pointer; line-height: 40px; text-align: center; font-weight: bold; font-family: '黑體'; font-size: 30px; color: #fff; opacity: 0.3; border: 1px solid #fff; } #arr #right { right: 5px; left: auto; }
</style> </head> <body> <div id="box" class="all"> <div class="ad"> <ul id="imgList"> <li><img src="images/1.jpg"/></li> <li><img src="images/2.jpg"/></li> <li><img src="images/3.jpg"/></li> <li><img src="images/4.jpg"/></li> <li><img src="images/5.jpg"/></li> </ul> </div> <div id="arr"><span id="left">&lt;</span><span id="right">&gt;</span></div> </div> <script type="text/javascript"> //需求 點選左右箭頭 以動畫效果移動ul到指定位置 //找人 var box = document.getElementById("box"); var ad = box.children[0]; var ul = document.getElementById("imgList"); var lis = ul.children; var arr = document.getElementById("arr"); var left = document.getElementById("left"); var right = document.getElementById("right"); var imgWidth = ad.offsetWidth; //滑鼠經過arr時,顯示arr內的元素,滑鼠離開時隱藏 box.onmouseover = function(){ arr.style.display = "block"; } box.onmouseout = function(){ arr.style.display = "none"; } //點選右箭頭,以動畫的形式,把ul移動到指定的位置 var pic = 0; //記錄當前顯示位置的索引 right.onclick = function(){ //先判斷 如果是最後一個圖片的索引,就不能再執行了 if(pic===lis.length-1){ return; } pic++; //目標 和pic有關,和圖片寬度有關 而且是負數 var target = -pic*imgWidth; animate(ul,target); } //點選左箭頭,以動畫的形式,把ul移動到指定的位置 left.onclick = function(){ //先判斷 如果是第一個圖片的索引,就不能再執行了 if(pic===0){ return; } pic--; //目標 和pic有關,和圖片寬度有關 而且是負數 var target = -pic*imgWidth; animate(ul,target); } function animate(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { var step = 20; var step = obj.offsetLeft < target ? step : -step; if (Math.abs(obj.offsetLeft - target) > Math.abs(step)) { obj.style.left = obj.offsetLeft + step + "px"; } else { obj.style.left = target + "px"; clearInterval(obj.timer); } }, 15) } </script> </body> </html>