一直覺得js學的不扎實,網(wǎng)上找了項目練手,項目地址在這里。
分析
- 幻燈片是通過設置
class="current"來更換圖片 和 改變圖片序號按鈕樣式的; - 通過設置
setInterval實現(xiàn)自動滾動; - 對圖片序號按鈕添加「鼠標懸停事件」。鼠標懸停,幻燈片切換到相應頁面;
- 鼠標停留在幻燈片上時,幻燈片不滾動。
實現(xiàn)
- 實現(xiàn)幻燈片自動滾動。
let list = document.querySelector(".list");
let count = document.querySelector(".count");
let timer = null;
let current_num = 1;
let last_num = 0;
window.addEventListener("load", function () {
timer = setInterval(function () {
if (current_num >= 5) {
current_num = 0;
}
list.children[last_num].className = "";
list.children[current_num].className = "current";
count.children[last_num].className = "";
count.children[current_num].className = "current";
last_num = current_num;
current_num += 1;
}, 1500);
}, false)
oh,my god。在設置class的時候犯傻了,竟然習慣性的把當作樣式經(jīng)進行修改。

1.gif
- 當然 這樣是不行的,還需要實現(xiàn)切換時的淡入淡出效果,使變化變得柔和。在樣式表中添加動畫效果。
<style>
#box .list li {
animation: wrap_opacity_0 1s linear forwards;
}
#box .list li.current {
animation: wrap_opacity_1 1s linear forwards;
}
@keyframes wrap_opacity_1 {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes wrap_opacity_0 {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
</style>

2.gif
- 為幻燈片添加鼠標事件。
//將計時器內部的函數(shù)提出,定義為 `f()` ,方便后面進行再次調用。
list.addEventListener("mouseenter", function () {
clearInterval(timer);
}, false);
list.addEventListener("mouseleave", function () {
timer = setInterval(f, 3000);
}, false)
- 為
count添加鼠標事件。
//對count添加事件,為子節(jié)點代理
count.addEventListener("mouseover", function (event) {
clearInterval(timer);
if (event.target.tagName.toLowerCase() === "li") {
//對count初始化
for (let i = 0; i < list.children.length; i++) {
list.children[i].className = "";
count.children[i].className = "";
}
current_num = Number(event.target.innerHTML) - 1;
if (current_num === 0) {
last_num = 4;
} else {
last_num = current_num - 1;
}
list.children[current_num].className = "current";
count.children[current_num].className = "current";
}
}, false);
count.addEventListener("mouseout", function () {
timer = setInterval(f, 3000);
})
完整代碼在這里
如有錯誤,歡迎指正。