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. 当然 这样是不行的,还需要实现切换时的淡入淡出效果,使变化变得柔和。在样式表中添加动画效果。
<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
  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);
  })

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 刚刚在翻15年的笔记,发现写了一段话现在也不记得是抄下来的还是自己写的,就是觉得超好笑的 “有时候的埋怨不是没有...
    ANDTHENIMEETYOU阅读 1,036评论 0 0
  • 富翁在海滨度假,见到一个垂钓的渔夫。富翁说,我告诉你如何成为富翁和享受生活的真谛。渔夫说,洗耳恭听。富翁说,首先,...
    刘虎虎222婚礼纪实阅读 1,405评论 1 1

友情链接更多精彩内容