js练习-自动播放一幻灯片效果

一直觉得js学的不扎实,网上找了项目练手,项目地址在这里。

分析

  1. 幻灯片是通过设置class="current"来更换图片 和 改变图片序号按钮样式的;
  2. 通过设置setInterval实现自动滚动;
  3. 对图片序号按钮添加「鼠标悬停事件」。鼠标悬停,幻灯片切换到相应页面;
  4. 鼠标停留在幻灯片上时,幻灯片不滚动。

实现

  1. 实现幻灯片自动滚动。
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的时候犯傻了,竟然习惯性的把当作样式经进行修改。

1.gif
  1. 当然 这样是不行的,还需要实现切换时的淡入淡出效果,使变化变得柔和。在样式表中添加动画效果。

2.gif
  1. 为幻灯片添加鼠标事件。
//将计时器内部的函数提出,定义为 `f()` ,方便后面进行再次调用。
list.addEventListener("mouseenter", function () {
  clearInterval(timer);
}, false);

list.addEventListener("mouseleave", function () {
  timer = setInterval(f, 3000);
}, false)
  1. count添加鼠标事件。
//对count添加事件,为子节点代理
  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);
  })

完整代码在这里
如有错误,欢迎指正。

你可能感兴趣的:(js练习-自动播放一幻灯片效果)