开发工具与关键技术:VS、JavaScript
作者:LJR
撰写时间:2019年 7 月 26 日
- 看到别人的网站的轮播特别好看,然后自己就利用原生JS做了一个轮播图片。
下面是HTML的代码格式:
<div class="con">
<div class="container" id="container">
<div class="list" id="list" style="left: -670px;">
<img src="图片的路径" alt="">
<img src="图片的路径" alt="">
<img src="图片的路径" alt="">
<img src="图片的路径" alt="">
<img src=".图片的路径" alt="">
<img src="图片的路径" alt="">
<img src="图片的路径" alt="">
</div>
<div class="bottons" id="bottons">
<span index="1" class="on">1</span>
<span index="2">2</span>
<span index="3">3</span>
<span index="4">4</span>
<span index="5">5</span>
</div>
<a href="javascript:void(0);" class="prev" id="prev"><</a>
<a href="javascript:;" class="next" id="next">></a>
</div>
</div>
这里不对图片进行Css的样式进行对图片的编辑;
下面是JavaScript的代码:
var tranfor=false;
var index=1;
var timer=null;
window.onload=function(){
var prev=document.getElementById("prev");
var next=document.getElementById("next");
var bottons=document.getElementById("bottons").getElementsByTagName("span");
var container=document.getElementById("container");
//onclick js单击事件
prev.onclick=function(){
if(index==1){
index=5;
}else{
index--;
}
if(tranfor==true){
return;
}
animate(670);
showbottons();
};
next.onclick=function(){
if(tranfor==true){
return;
}
if(index==5){
index=1;
}else{
index++;
}
animate(-670);
showbottons();
};
for(var i=0;i<bottons.length;i++){
/*console.log(bottons[i]);*/
bottons[i].onclick=function(){
/*alert(23);*/
if(tranfor==true){
return;
}
var myindex=this.getAttribute("index");
/*alert(myindex);*/
var offset=-670*(myindex-index);
animate(offset);
index=myindex;
showbottons();
};
}
function play(){
timer=setInterval(function(){
next.onclick();
},2000);
}
function stopPlay(){
clearInterval(timer);
}
play();
container.onmousemove=stopPlay;
container.onmouseout=play;
};
function animate(offset){
tranfor=true;
var list=document.getElementById("list");
var newleft=0;
var time=300;//300ms 总的运行时间
var interval=10;//间隔时间 总的运行次数=time/interval
var speed=offset/(time/interval);//每次运动的距离
newleft=parseInt(list.style.left)+offset;//parseInt() 将字符串 转换为一个数字类型
function go(){
if((speed<0&&parseInt(list.style.left)>newleft)||(speed>0&&parseInt(list.style.left)<newleft)){
list.style.left=parseInt(list.style.left)+speed+"px";
setTimeout(go,interval);//
}else{
list.style.left=newleft+"px";
if(newleft>-670){
list.style.left=-670*5+"px";
}
if(newleft<-670*5){
list.style.left=-670+"px";
}
tranfor=false;
}
}
go();
}
function showbottons(){
var buttons=document.getElementById("bottons").getElementsByTagName("span");
for(var i=0;i<buttons.length;i++){
if(buttons[i].className=="on"){
buttons[i].className="";
break;
}
}
buttons[index-1].className="on";
}
一个简单的轮播这样就做出来了。