1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| let banner = document.getElementById("banner"); let wrapper = document.getElementById("wrapper"); let list = document.getElementById("list"); let lis = list.getElementsByTagName("li");
let data = null;
let timer = null;
let step = 0;
function animate(ele, target, duration) { let begin = {} let change = {} for (const key in target) { begin[key] = parseFloat(window.getComputedStyle(ele)[key]) change[key] = target[key] - begin[key] } let time = 0 let timers = setInterval(() => { time += 20 for (const key in target) { ele.style[key] = time / duration * change[key] + begin[key] + "px"; } if (time >= duration) { clearInterval(timers); } }, 20) }
function getData(url) { let xhr = new XMLHttpRequest(); xhr.open("get", url, false); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { data = JSON.parse(xhr.responseText); renderHtml(data); } }; xhr.send(); } getData("./banner.json");
function renderHtml(data) { let imgs = ""; let lis = ""; data.forEach((item, index) => { imgs += `<li><img src="${item.img}" alt=""></li>`; lis += "<li></li>"; }); imgs += `<li><img src="${data[0].img}" alt=""></li>`; wrapper.innerHTML = imgs; list.innerHTML = lis; }
function autoMove(index) { step++; typeof index == "undefined" ? null : step = index; if (step >= data.length + 1) { wrapper.style.left = 0; step = 1; } animate(wrapper, { left: -1226 * step }, 500); changeFocus(); } timer = setInterval(autoMove, 2000);
banner.onmouseover = function () { clearInterval(timer); } banner.onmouseout = function () { clearInterval(timer); timer = setInterval(autoMove, 2000); }
function changeFocus() { for (let i = 0; i < lis.length; i++) { if (i == step) { lis[i].classList.add("active"); } else { lis[i].classList.remove("active"); } } if (step == data.length) { lis[0].classList.add("active"); } } changeFocus();
function bindClick() { for (let i = 0; i < lis.length; i++) { lis[i].onclick = function () { autoMove(i); } } } bindClick();
right.onclick = debounce(autoMove, 300); function lClick() { if (step == 0) { step = data.length; wrapper.style.left = (data.length) * -1226 + "px"; } step--; autoMove(step) } left.onclick = debounce(lClick, 300)
function debounce(fn, wait) { let timers = null; let result = null; return function (...args) { if (timers) clearTimeout(timers); timers = setTimeout(() => { result = fn.apply(this, ...args); }, wait) return result; } }
|