js轮播图
html部分:建立div,内嵌img标签,可以设置大小,
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script type="text/javascript" src="untitled1.js"></script> </head> <body> <div id="quyu" style=" 1000px;height: 500px;background: #3BE3C6;margin: 0 auto" > <img id="im" onMouseOver="stop()" onMouseOut="start()" src="../../1.jpg" alt="" height="500px" width="1000px"> </div> <center> <button onClick="before()">上一页</button> <button class="butt" onClick="xx(0)" style="color: red;">1</button> <button class="butt" onClick="xx(1)">2</button> <button class="butt" onClick="xx(2)">3</button> <button class="butt" onClick="xx(3)">4</button> <button onClick="next()">下一页</button> </center> </body> </html>
js部分
设置全局变量,表示图片地址数组的下标
轮播功能,设置定时器,定时替换图片地址
鼠标移入,定时器停止
鼠标移出,再次设置定时器
上一页,全局变量减1
下一页,全局变量加1
// JavaScript Document var n = 0; //图片下标 var imDom = null; //图片 var imPath = ["../../1.jpg", "../../2.jpg", "../../3.jpg", "../../4.jpg"];//图片位置 var intervalobj = null;//定时器 var btnDom = null;//数字按钮 window.onload = function () { imDom = document.getElementById("im"); btnDom = document.getElementsByClassName("butt"); intervalobj = setInterval(function () { lunbo(); }, 3000); } /*功能:图片轮播*/ function lunbo() { n++; if (n >= imPath.length) { n = 0; } imDom.src = imPath[n]; for (var i = 0; i < btnDom.length; i++) { btnDom[i].style.color = "black"; } btnDom[n].style.color = "red"; } /*鼠标移入,轮播停止*/ function stop() { clearInterval(intervalobj); } /*鼠标移入 轮播继续*/ function start() { intervalobj = setInterval(function () { lunbo(n); n++; if (n >= imPath.length) { n = 0; } }, 3000); } /*图片进入上一页*/ function before() { n--; if (n <=-1) { n = imPath.length-1; } imDom.src = imPath[n]; for (var i = 0; i < btnDom.length; i++) { btnDom[i].style.color = "black"; } btnDom[n].style.color = "red"; } /*图片进入下一页*/ function next() { n++; if (n >= imPath.length) { n = 0; } imDom.src = imPath[n]; for (var i = 0; i < btnDom.length; i++) { btnDom[i].style.color = "black"; } btnDom[n].style.color = "red"; } /*点击数字按钮,跳转到相应图片*/ function xx(a) { imDom.src = imPath[a]; }