js上课小案例,利用定时器完成幻灯片的自动播放。
注意定时器的开和关。
具体效果点击查看
1、html代码
<div class="banner"> <ul class="pic-lists"> </ul> <ul class="title-lists"> </ul> <span class="btn prev"><i class="iconfont icon-left"></i></span> <span class="btn next"><i class="iconfont icon-right"></i></span> </div>
2、css代码
* { box-sizing: border-box; } body, ul, li { margin: 0; padding: 0; } li { list-style: none; } img { border: none; vertical-align: middle; } .banner { position: relative; width: 850px; height: 394px; overflow: hidden; margin:20px auto; } .title-lists, .pic-lists { display: flex; transition: 0.2s ease-out; } .title-lists { justify-content: space-around; background-color: #f5f5f5; } .title-lists { height: 44px; line-height: 44px; } .title-lists a { color: #525252; text-decoration: none; font-size: 0.875rem; } .title-lists a:hover, .title-lists li.active { color: #ff6000; } .title-lists li.active { color: #ff6000; border-bottom: 5px solid #ff6000; } .btn { position: absolute; width: 40px; height: 80px; left: 0; top: 50%; margin-top: -62px; background-color: rgba(0, 0, 0, 0.2); color: #fff; text-align: center; line-height: 80px; cursor: pointer; transition: 0.2s; } .btn:hover { background-color: rgba(0, 0, 0, 0.3) } .btn .iconfont { font-size: 1.25rem; } .btn.next { right: 0; left: auto; }
3、js代码
<script> // 找对象 var oDiv = document.querySelector(".banner"); var oPic = oDiv.querySelector(".pic-lists"); var oList = oDiv.querySelector(".title-lists"); var oLi = oList.getElementsByTagName("li"); var oPrev = oDiv.querySelector(".prev"); var oNext = oDiv.querySelector(".next"); // 存放有active的li对象 var oldLi = null; // 定义一个定时器对象 var timer = null; // 初始化值 var url = ["images/1.png", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.jpg", "images/6.jpg"]; var title = ["手绘课程", "手绘技法", "ps合成", "品牌设计", "海报设计", "软件班"]; // 初始化结构 url.forEach(function (item) { oPic.innerHTML += "<li><a href='#'><img src='" + item + "'></a></li>" }) title.forEach(function (item) { oList.innerHTML += "<li><a href='#'>" + item + "</a></li>" }) var num = 0; var len = url.length; var liArr = [...oLi]; oPic.style.width = 850 * len + "px"; tab(); autoPlay(); // 鼠标经过和移开关闭和启动自动播放 oDiv.onmouseover = function () { clearInterval(timer); } oDiv.onmouseout = function () { autoPlay(); } // 点击上一张下一张切换 oNext.onclick = function () { num++; if (num >= len) { num = 0; } oldLi.classList.remove("active"); tab(); } oPrev.onclick = function () { num--; if (num <= -1) { num = len - 1; } oldLi.classList.remove("active"); tab(); } // 标题点击切换 liArr.forEach(function (item, index) { item.onclick = function () { num = index; oldLi.classList.remove("active"); tab(); } }) function tab() { oPic.style.transform = "translateX(-" + num * 850 + "px)"; oLi[num].classList.add("active"); oldLi = oLi[num]; } // 定时器自动执行 function autoPlay() { timer = setInterval(function () { num++; if (num >= len) { num = 0; } oldLi.classList.remove("active"); tab(); }, 3000); } </script>
发表评论:
◎请发表你卖萌撒娇或一针见血的评论,严禁小广告。