標籤:
思路:
總結:1. 給迴圈與否設定標識 isLoop ,true為迴圈2. 下一張到最後一張的時候, 迴圈則 index 變成0 , 否則停留在最後一張,下標為arrImg.length-1 上一張到第一張的時候, 迴圈則跑到最後一張, 否則停留在第一張3.當下標發生變化的時候, 哪些東西要改變? 圖片 , 圖片頂部的文字, 圖片下面的文字資訊
1. 效果
2. 代碼
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> p { margin:0; } body { text-align:center; } #box { width:400px; height:400px; border:10px solid #ccc; margin:50px auto 0; position:relative; } a { width:40px; height:40px; background:#fff; filter:alpha(opacity:80); opacity:0.8; position:absolute; top:160px; font-size:18px; color:#000; text-align:center; line-height:40px; text-decoration:none; } a:hover { filter:alpha(opacity:30); opacity:0.3; } #prev { left:10px; } #next { right:10px; } #p1 { width:400px; height:30px; line-height:30px; text-align:center; background:#000; color:#fff; font-size:14px; filter:alpha(opacity:80); opacity:0.8; position:absolute; bottom:0; left:0; } strong { width:400px; height:30px; line-height:30px; text-align:center; background:#000; color:#fff; font-size:14px; filter:alpha(opacity:80); opacity:0.8; position:absolute; top:0; left:0; } #img1 { width:400px; height:400px; } span { position:absolute; width:400px; height:30px; line-height:30px; text-align:center; top:-50px; left:0; font-family:‘微軟雅黑‘; } </style></head><body><input type="button" value="迴圈播放圖片"><input type="button" value="順序播放圖片"><div id="box"> <span>圖片可從最後一張跳轉到第一張迴圈切換</span> <a id="prev" href="javascript:;"><</a> <a id="next" href="javascript:;">></a> <p id="p1">圖片文字載入中...</p> <strong id="strong1">圖片數量計算中...</strong> <img id="img1"></div><script> window.onload = function () { var aBtn = document.getElementsByTagName(‘input‘) var oSpan = document.getElementsByTagName(‘span‘) var oPrev = document.getElementById(‘prev‘) var oNext = document.getElementById(‘next‘) var oP = document.getElementById(‘p1‘) var oStrong = document.getElementById(‘strong1‘) var oImg = document.getElementById(‘img1‘) var arrImg = [‘img/1.png‘,‘img/2.png‘,‘img/3.png‘,‘img/4.png‘,] var arrText = [ ‘文字一‘, ‘文字二‘, ‘文字三‘, ‘圖片4‘ ]; var index = 0; var isLoop = true; init(); aBtn[0].onclick = function () { isLoop = true; oSpan[0].innerHTML = ‘迴圈輪播 :圖片可從最後一張跳轉到第一張迴圈切換‘; oSpan[0].style.color = ‘red‘; } aBtn[1].onclick = function () { isLoop = false; oSpan[0].innerHTML = ‘順序:圖片只能到最後一張\或只能到第一張切換‘; oSpan[0].style.color = ‘red‘; } oNext.onclick = function () { index++; if (index == arrImg.length){ isLoop ? index = 0 : index = arrImg.length-1; } init(); } oPrev.onclick = function () { index--; if (index == -1){ isLoop ? index = arrImg.length - 1 : index = 0; } init(); } function init() { oP.innerHTML = arrText[index]; oImg.src = arrImg[index]; oStrong.innerHTML = (index+1)+ ‘/‘ + arrImg.length; } }</script></body></html>
js - 02課 - 圖片迴圈順序切換執行個體