您的位置:首页 > Web前端 > JavaScript

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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: