關於輪播圖(1)
阿新 • • 發佈:2018-11-11
不瞞大家說,輪播圖簡直是我的噩夢,就像是論文之於大學生[受虐滑稽][受虐滑稽]
簡單輪播圖
最簡單的輪播圖,用WebAPI做的,點選圖片底下的數字跳轉到相對應的圖片。
1、首先把結構寫出來
<div class="box" id="box"> <div class="inner"> <ul> <li><a href="#"><img src="http://hbimg.b0.upaiyun.com/074d5ab1e10bb890a8088867bd1bc7f6ca09272a19f114-J0kTnl_fw658" alt=""/></a></li> <li><a href="#"><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542521291&di=1be438987e94a93cb5d77d4384f28f58&imgtype=jpg&er=1&src=http%3A%2F%2Fimgcache.cjmx.com%2Fstar%2F201608%2F20160823141712357.jpg" alt=""/></a></li> <li><a href="#"><img src="http://upload.taihainet.com/2016/0807/1470581312169.gif?size=500x300" alt=""/></a></li> </ul> <div class="square"> <span class="current">1</span> <span>2</span> <span>3</span> </div> </div> </div>
2、新增style樣式
<style> * { margin: 0; padding: 0 } ul { list-style: none } img { vertical-align: top } .box { width: 500px; height: 300px; margin: 100px auto; padding: 5px; border: 1px solid #ccc; } .inner { width: 500px; height: 300px; background-color: pink; overflow: hidden; position: relative; } .inner ul { width: 1000%; position: absolute; top: 0; left: 0; } .inner li { float: left; } .square { position: absolute; right: 10px; bottom: 10px; } .square span { display: inline-block; width: 16px; height: 16px; background-color: #fff; text-align: center; line-height: 16px; cursor: pointer; } .square span.current { background-color: orangered; color: #fff; } </style>
3、script
<script> //1 獲取元素 var box = document.getElementById("box"); var inner = box.children[0];//可視區域 var list = inner.children[0];//要運動的列表 var spans = inner.children[1].children;//要操作的所有按鈕 var imgWidth = inner.offsetWidth;//獲取了可視區域的寬度 //2 步驟分析: //2.1點選spans進行操作 //2.2 點選按鈕變色效果 //2.3 設定list的運動位置 //點選按鈕1 left為 - 0 * 圖寬 //點選按鈕2 left為 - 1 * 圖寬 //點選按鈕3 left為 - 2 * 圖寬 //通過觀察我們發現,list要設定的left值為 - 按鈕索引值 * 圖片寬度 //3 具體操作 //遍歷 for (var i = 0; i < spans.length; i++) { spans[i].index = i; spans[i].onclick = function () { //點選按鈕變色 for (var i = 0; i < spans.length; i++) { spans[i].className = ""; } this.className = "current"; //根據規律設定運動位置 animate(list, -this.index * imgWidth); }; } function animate(element, target) { clearInterval(element.timer);//清除舊的定時器,保證勻速運動,防止加速效果 element.timer = setInterval(function () { //1 獲取元素當前位置 使用offsetLeft屬性 var current = element.offsetLeft; //2 設定步長,隨意設定,不過最好是整數 var step = 17; //根據當前位置和目標位置的大小關係進行判斷 step = target > current ? step : -step; //5 運動條件設定 //檢測當前位置和目標位置之間的距離,如果滿足一個step的距離,可以運動,否則直接運動到目標位置,結束 if (Math.abs(target - current) > Math.abs(step)) { //3 設定運動公式:元素位置(新) = 元素位置(舊) + 步長; current = current + step; //4 設定給元素的left值運動 element.style.left = current + "px"; } else { //6 讓element直接運動到目標位置,再清除定時器 element.style.left = target + "px"; clearInterval(element.timer); } }, 20); } </script>
差不多該寫的都寫上了,這是我第一個輪播圖,最簡單、最低階的輪播圖,適合小小白看,這幾天還會更新其他的輪播圖。