原生 JavaScript 实现图片切换

原生 JavaScript 实现图片切换

JavaScript实现图片切换的介绍

使用原生JavaScript实现点击按钮图片切换
html css JavaScript
原理:使用原生JavaScript,获取点击事件,改变显示图片位置的路径

效果

在这里插入图片描述

html代码

<body>

	<div id="box">
	    
		<div id="left"></div>
		 
		<ul id="ul">
		    <li>
			    <img id="oImg" src="img/1.jpg" style="width:420px; height:500px;" />
			</li>
		</ul>
		
		<div id="right"></div>
		
	</div>

</body>

css代码

<style>
	    #box{
		   position:relative;
		   width:420px;
		   height:500px;
		   margin:100px auto;
		}
		#left,#right{
		   position:absolute;
		   width:50px;
		   height:80px;
		   background:#00FFFF;
		   top:200px;
		   z-index:9;
		}
		#left{
		   left:5px;
		   display:none;
		   background:url(img/7.png) no-repeat;
		   background-size:50px 80px;
		}
		#right{
		   right:5px;
		   display:none;
		   background:url(img/6.png) no-repeat;
		   background-size:50px 80px;
		}
		#ul{
		    width:420px;
			height:500px;
		    margin:0;
			padding:0;
			list-style:none;
			overflow:hidden;
		}
		#ul li{
		    width:420px;
			height:500px;
			z-index:1;
		}
	</style>

JavaScript代码

<script>
  
    var oBox=document.getElementById('box');

	var oLeft=document.getElementById('left');
    var oRight=document.getElementById('right');
	var oImg=document.getElementById('oImg');
	   
	var Smax=5,Smin=1,Sm=Smin;
	
	oBox.onmouseover=function(){
	    
		 oLeft.style.display='block';
		 oRight.style.display='block';
		 
	};
	
	oBox.onmouseout=function(){
	    
		 oLeft.style.display='none';
		 oRight.style.display='none';
		 
	};
	
	oLeft.onclick=function(){
	
		 if(Sm===Smin)
		 {
			 Sm=Smax;
		 }
		 else
		 {
			  Sm--;
		 }
	    
		 oImg.src='img/'+Sm+'.jpg';
		 //console.log(oImg.src);
		 
    };
	   
	oRight.onclick=function(){
	
		 if(Sm===Smax)
		 {
			 Sm=Smin;
		 }
		 else
		 {
			  Sm++;
		 }
	    
		 oImg.src='img/'+Sm+'.jpg';
		 console.log(oImg.src);
		 
    };
	


</script>

效果

在这里插入图片描述

在这里插入图片描述

总结

通过 JavaScript 点击事件,获取点击按钮,是左或是右,通过添加按钮的方向,判断图片切换的方向,点击一下,图片的路径随之切换一下。

发布了7 篇原创文章 · 获赞 9 · 访问量 1458

猜你喜欢

转载自blog.csdn.net/weixin_44134972/article/details/85333051