基于javascript实现图片切换效果
本文实例为大家分享了js实现图片切换效果,供大家参考,具体内容如下
用js实现点击按钮,图片切换的效果:
<divclass="box"id="box"> <divclass="img_box"id="img_box"> <imgsrc="../raw/b1.jpg"class="image"> <imgsrc="../raw/b2.jpg"class="image"> <imgsrc="../raw/b3.jpg"class="image"> <imgsrc="../raw/b4.jpg"class="image"> </div> <divid="left"class="switch"></div> <divid="right"class="switch"></div> </div>
结构:用一个固定宽高的div来做最外层的容器,设置overflow为hidden,
然后内层img_box设置宽度为四倍box的宽度,高度相同,也就是说img_box里面盛放四张img,但是可见的只有一张,下面的两个div,left和right是充当按钮实现点击切换图片,切换图片也就是改变img_box的left属性,所以img_box应该设置position为absolute,为了方便起见,box的position设置为relation,这样img_box就是相对box进行定位了。四张图片设置float为left,宽度和高度与box相同.
CSS代码:
*{
margin:0;
padding:0;
}
.box{
width:800px;
height:400px;
margin:20pxauto;
position:relative;
overflow:hidden;
}
.img_box{
height:400px;
width:3200px;
position:absolute;
-moz-transition:0.5s;
-webkit-transition:0.5s;
}
img{
width:800px;
height:400px;
float:left;
}
.switch{
width:200px;
height:100%;
position:absolute;
}
#left{
left:0px;
top:0px;
background:-moz-linear-gradient(left,rgba(84,84,84,0.50),rgba(20%,20%,20%,0));
background:-webkit-linear-gradient(left,rgba(84,84,84,0.50),rgba(20%,20%,20%,0));
}
#right{
right:0px;
top:0px;
background:-moz-linear-gradient(left,rgba(20%,20%,20%,0),rgba(84,84,84,0.5));
background:-webkit-linear-gradient(left,rgba(20%,20%,20%,0),rgba(84,84,84,0.5));
}
#left:hover{
background:-moz-linear-gradient(left,rgba(0,0,0,0.5),rgba(20%,20%,20%,0));
background:-webkit-linear-gradient(left,rgba(0,0,0,0.5),rgba(20%,20%,20%,0));
}
#right:hover{
background:-moz-linear-gradient(left,rgba(20%,20%,20%,0),rgba(0,0,0,0.5));
background:-webkit-linear-gradient(left,rgba(20%,20%,20%,0),rgba(0,0,0,0.5));
}
left和right用到了背景颜色和透明度渐变的属性,只添加了火狐浏览器和webkit浏览器,另外现在有的IE浏览器是IE和webkit双内核如360安全浏览器
background:-moz-linear-gradient(left,rgba(84,84,84,0.50),rgba(20%,20%,20%,0));
background:-webkit-linear-gradient(left,rgba(84,84,84,0.50),rgba(20%,20%,20%,0));
为了实现切换的时候平滑过渡,所以添加了transition属性:
-moz-transition:0.5s;
-webkit-transition:0.5s;
js代码:
varbox;
varcount=1;
window.onload=function(){
box=document.getElementById("img_box");
varleft=document.getElementById("left");
varright=document.getElementById("right");
left.addEventListener("click",_left);
right.addEventListener("click",_right);
document.body.addEventListener("mouseover",demo);
}
function_right(){
vardis=0;
if(count<4){
dis=count*800;
}else{
dis=0;
count=0;
}
box.style.left="-"+dis+"px";
count+=1;
}
function_left(event){
vardis=0;
if(count>1){
dis=(2-count)*800;
}else{
dis=-3*800;
count=5;
}
box.style.left=dis+"px";
count-=1;
}
用全局变量count来记录当前显示的第几张图片,当点击切换按钮的时候根据count来计算应该显示第几张照片,然后计算并设置img_box的left属性即可。
以上就是为大家介绍的js实现图片切换效果的代码,希望能够帮助大家实现图片切换效果。