JS初学之-if else图片顺序及循环切换

时间:2023-03-10 06:32:37
JS初学之-if else图片顺序及循环切换

初学JS,代码还需多多改进,自学中...

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
p { margin:0; }
body { text-align:center; }
#box { width:400px; height:400px; border:10px solid #ccc; margin:50px auto 0; position:relative; }
a { width:40px; height:40px; background:#fff; filter:alpha(opacity:80); opacity:0.8; position:absolute; top:160px; font-size:18px; color:#000; text-align:center; line-height:40px; text-decoration:none; }
a:hover { filter:alpha(opacity:30); opacity:0.3; }
#prev { left:10px; }
#next { right:10px; }
#p1 { width:400px; height:30px; line-height:30px; text-align:center; background:#000; color:#fff; font-size:14px; filter:alpha(opacity:80); opacity:0.8; position:absolute; bottom:0; left:0; }
strong { width:400px; height:30px; line-height:30px; text-align:center; background:#000; color:#fff; font-size:14px; filter:alpha(opacity:80); opacity:0.8; position:absolute; top:0; left:0; }
#img1 { width:400px; height:400px; }
span { position:absolute; width:400px; height:30px; line-height:30px; text-align:center; top:-50px; left:0; font-family:'微软雅黑'; }
</style>

</head>

<body>
<input type="button" value="循环切换" />
<input type="button" value="顺序切换" />

<div id="box"><span>图片可从最后一张跳转到第一张循环切换</span>
<a id="prev" href="javascript:;"><</a>
<a id="next" href="javascript:;">></a>
<p id="p1">图片文字加载中……</p>
<strong id="strong1">图片数量计算中……</strong>
<img id="img1" />
</div>
<script>
var aBtn=document.getElementsByTagName('input');
var oImg=document.getElementById('img1');
var oPrev=document.getElementById('prev');
var oNext=document.getElementById('next');
var oP=document.getElementById('p1');
var oSpan=document.getElementsByTagName('span')[0];
var oP=document.getElementById('p1');
var aImg=['img/1.jpg', 'img/2.jpg', 'img/3.jpg', 'img/4.jpg'];
var aText=['图片1','图片2','图片3','图片4'];
var oStrong=document.getElementById('strong1');
var num=0;
var onOff=true;
//初始化
function tab(){
oStrong.innerHTML=num+1+'/'+aImg.length;
oP.innerHTML=aText[num];
oImg.src=aImg[num];
};
tab();

aBtn[0].onclick=function(){
onOff;
oSpan.innerHTML='图片可从最后一张跳转到第一张循环切换';
};
aBtn[1].onclick=function(){
onOff=false;
oSpan.innerHTML='顺序切换';
};

oPrev.onclick=function(){
num--;
if(num==-1){
if(onOff){
num=aImg.length-1;
}else{num=0};
};
tab();
};
oNext.onclick=function(){
num++;
if(num==aImg.length){
if(onOff){
num=0;
}else{num=aImg.length-1};
};
tab();
};
</script>
</body>
</html>