javascript中用三元运算符实现手动图片转换

主要思想为:

一:布局HTML部分主要是img图片和两个按钮(next和prev),

<img id="image" src="image/1.jpg" />
<button id="next" style="size:12px" onClick="nn()">next</button>
<button id="prev" style="size:12px"  onClick="pp()">prev</button>

二:js部分主要是利用变量nowIndex来控制src的来源图片是哪一个

先定义各个变量:

var image=document.getElementById("image");
var next=document.getElementById("next");
var prev=document.getElementById("prev");
var nowIndex=1;
var count=5;

然后主要功能实现: 

function nn(){
    nowIndex=nowIndex+1>count?1:nowIndex+1;
     image.src="image/"+nowIndex+".jpg";
    }
   function pp(){
    nowIndex=nowIndex<2?count:nowIndex-1;
     image.src="image/"+nowIndex+".jpg";
    }

也可以直接用对象和方法来进行

  next.οnclick=function() {
    nowIndex=nowIndex+1>count?1:nowIndex+1;
     image.src="image/"+nowIndex+".jpg";
    }

 prev.οnclick=function (){
    nowIndex=nowIndex<2?count:nowIndex-1;
     image.src="image/"+nowIndex+".jpg";
    }

以下是完整代码

扫描二维码关注公众号,回复: 11251369 查看本文章

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>手动图片切换</title>
<style type="text/css">
#image{ display:block;
width:500px;
height:180px;
margin:10px auto;
    
    }
#next{ margin-left:800px;
    }
</style>

</head>

<body>

<img id="image" src="image/1.jpg" />
<button id="next" style="size:12px" onClick="nn()">next</button>
<button id="prev" style="size:12px"  onClick="pp()">prev</button>
<script language="javascript">
var image=document.getElementById("image");
var next=document.getElementById("next");
var prev=document.getElementById("prev");
var nowIndex=1;
var count=5;
  function nn(){
    
    nowIndex=nowIndex+1>count?1:nowIndex+1;
     image.src="image/"+nowIndex+".jpg";
    }
   function pp(){
    
    nowIndex=nowIndex<2?count:nowIndex-1;
     image.src="image/"+nowIndex+".jpg";
    }
</script>
</body>
</html>

具体效果如下:

猜你喜欢

转载自blog.csdn.net/weixin_45147894/article/details/106291898