简易轮播图、内含定时器。熟练JS操作

HTML部分:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src = "lunbotu.js"></script>
<style>
#kuai{
width: 50%;
height: 300px;
margin: auto;
position: relative;
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
}
#kuai img{
width: 100%;
height: 100%;
}
#btn_1{
position: absolute;
top: 50%;
left: 0px;
}
#btn_2{
position: absolute;
top: 50%;
right: 0px;
}
#botBtn{
width: 300px;
height: 25px;
background-color: #ccc;
position: absolute;
bottom: 0px;
left: 30%;
}
.redC{
color: red;
}
</style>
</head>
<body>
<div id="kuai">
<!-- 在页面上显示一张图片 -->
<div id="tupian">
<img onmouseover="qingchudsq()" onmouseout="go_on()" src="image/J1.png" alt="">
</div>
<!-- 换行需要一个按钮需要一个按钮,叫下一页 -->
<button onclick="xiayiye()" id="btn_1">下一页</button>
<button onclick="shangyiye()" id="btn_2">上一页</button>
<div id="botBtn">
</div>
</div>
</body>
</html>

JS部分:

 

var imgObj = null;
// 定义一个数组存放src路径
var imgArrObj = ['image/J1.png','image/J2.png','image/J3.png','image/J4.png'];
var i = 0;//下标
var a = null;
var box = null;

window.onload = function(){
init();//初始化变量
dingshiqi();// 定时器
addBtn();//添加按钮
}
function init(){
imgObj = document.getElementsByTagName('img')[0];
box = document.getElementById('botBtn');
}
//变色
function bianse(){
//找到所有
var btns = box.getElementsByTagName('button');
// 删除class
for (var k = 0; k < btns.length; k++) {
btns[k].removeAttribute('class');
}
btns[i].setAttribute('class','redC');
}
// 下一页
function xiayiye(){
// 替换属性值
// 改变下标
i++;
if (i >= imgArrObj.length ){
i =0;
}
imgObj.setAttribute('src',imgArrObj[i]);
bianse();

}
//上一页
function shangyiye(){
i--;
if (i < 0) {
i = imgArrObj.length - 1;
}
imgObj.setAttribute('src',imgArrObj[i]);
bianse();
}
//定时器
function dingshiqi(){
a = setInterval(function(){
xiayiye();
// i++;
// if (i >= imgArrObj.length ){
// i =0;
// }
// imgObj.setAttribute('src',imgArrObj[i]);
},2000);
}

function addBtn(){
var str = '';
for (var k = 0;k < imgArrObj.length;k++) {
if (k==0) {
str += '<button class="redC" onclick="ch('+k+')">'+ (k+1) +"</button>";
}else{
str += '<button onclick="ch('+k+')">'+ (k+1) +"</button>";
}
}
box.innerHTML = str;
}
function ch(num){
i = num;
imgObj.setAttribute('src',imgArrObj[i]);
bianse();
}
// 清除定时器
function qingchudsq(){
clearInterval(a);
}
function go_on(){
dingshiqi();
}

posted @ 2019-04-15 21:06  IceK夏  阅读(254)  评论(0编辑  收藏  举报