JavaScript实现图片轮播器
2016-06-15 21:48
477 查看
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片轮播器</title> <link rel="stylesheet" type="text/css" href="pics.css"> </head> <body> <div class="box" id="box"> <div class="imgs" id="imgs"></div> <div class="btns" id="btns"></div> </div> </body> <script type="text/javascript" src="pics.js"></script> </html>
JavaScript
/*** Created by zmx on 16/6/15.*/var imgDiv = document.getElementById("imgs");var btnDiv = document.getElementById("btns");for(var i = 0; i < 4; i++) {var img = document.createElement("img");img.src = "images/" + i + ".jpg";imgDiv.appendChild(img);var btn = document.createElement("button");btn.innerText = i + 1;btn.setAttribute("class", "btn");btn.setAttribute("id", "btn" + i);btn.setAttribute("type", "button");btnDiv.appendChild(btn);}var imgs = imgDiv.getElementsByTagName("img");var btns = btnDiv.getElementsByTagName("button");var selectedIndex = -1;function select(index) {if(selectedIndex >= 0) {btns[selectedIndex].style.background = "black";}btns[index].style.background = "red";imgDiv.style.left = -600 * index + "px";selectedIndex = index;}select(0);var time= null;function run() {time = setInterval(function() {var index = selectedIndex;index++;if(index >= btns.length) {index = 0;}select(index);}, 2000);}run();for(var i in imgs) {imgs[i].onmouseover = function() {clearInterval(time);}imgs[i].onmouseout = function() {run();}}for(var i in btns) {btns[i].onclick = function() {clearInterval(time);select(this.getAttribute("id").substr(3));run();}btns[i].onmouseover = function() {this.style.background = "red";}btns[i].onmouseout = function() {if(this.getAttribute("id").substr(3) != selectedIndex) {this.style.background = "black";}}}
CSS
*{margin: 0;padding: 0;}.box{width: 600px;height: 400px;overflow: hidden;position: absolute;left: 20px;top: 20px;}.imgs{width: 2400px;height: 400px;position: absolute;}.imgs img{width: 600px;height: 400px;position: relative;top: 0;}.btns{width: 196px;height: 20px;position: absolute;right: 0;bottom: 0;overflow: hidden;}.btns button{width: 50px;height: 20px;border: 0;border-left: 1px solid white;margin-left: -1px;outline: none;font-size: 0.8em;color: white;background: black;}
相关文章推荐
- js中的DOM操作上(参考慕课网)
- 理解JS函数中的参数
- rest接口设计之--返回值设计
- 远程服务器存储之JSON
- js页面跳转整理
- JavaScript实现选项卡效果
- js 类的简单实现与调用
- js中使用另外一个js文件的变量
- 安卓.点击头像-->编辑个人姓名-->提交后.同时调用js关闭页面-->返回上一层
- JS闭包那些事
- JSP中的MIME
- js函数(类)的继承机制的设计与实现(五)
- BZOJ4488: [Jsoi2015]最大公约数
- json和xml的区别
- js限制文本框只能输入数字方法小结
- JS的解析机制
- Javascript笔记——数组
- JS中函数之外不能写return
- javascript类型系统——Number数字类型
- JavaScript 原型、原型链与继承