javascript实现图片轮播效果

2019-04-15 14:54发布

目录

文章目录

效果预览

本章将实现以下效果:
这里写图片描述

HTML代码

<div class="wrap" id='wrap'> <ul id="pic" class="pic"> <li><img src="image/picRoller1.jpg" alt="">li> <li><img src="image/picRoller2.jpg" alt="">li> <li><img src="image/picRoller3.jpg" alt="">li> ul> <ul id="list" class="list"> <li class="on">1li> <li>2li> <li>3li> ul> div>

CSS代码

.wrap { height: 360px; width: 990px; overflow: hidden; position: relative; margin-left: 190px; margin-top: 15px; top: 10px; bottom: 5px; } .wrap img { height: 360px; width: 990px; } .pic { position: absolute; } .list { position: absolute; right: 5px; bottom: 10px; } .list li { height: 20px; width: 20px; background: white; margin-left: 5px; color: #000; float: left; line-height: 20px; text-align: center; cursor: pointer; list-style: none; } .list .on { background: #E97305; color: #fff; }

JavaScript代码

window.onload = function () { var wrap = document.getElementById('wrap'), pic = document.getElementById('pic').getElementsByTagName("li"), list = document.getElementById('list').getElementsByTagName('li'), index = 0, timer = null; // 遍历所有数字导航实现划过切换至对应的图片 for (var i = 0; i < list.length; i++) { list[i].onmouseover = function () { clearInterval(timer); index = this.innerText - 1; changePic(index); }; } function autoPlay () { if (++index >= pic.length) index = 0; changePic(index); } // 定义图片切换函数 function changePic (curIndex) { for (var i = 0; i < pic.length; ++i) { pic[i].style.display = "none"; list[i].className = ""; } pic[curIndex].style.display = "block"; list[curIndex].className = "on"; } // 定义并调用自动播放函数 timer = setInterval(autoPlay, 3000); // 鼠标划过整个容器时停止自动播放 wrap.onmouseover = function () { clearInterval(timer); }; // 鼠标离开整个容器时继续播放至下一张 wrap.onmouseout = function () { timer = setInterval(autoPlay, 3000); }; };