<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#app {
width: 600px;
height: 600px;
border: 1px solid #000;
position: relative;
margin: 0 auto;
text-align: center;
}
#app img {
position: absolute;
width: 500px;
height: 500px;
display: none;
left: 50px;
top: 50px;
}
#app img.choose {
display: block;
}
#but {
margin: 10px auto 10px;
text-align: center;
}
</style>
</head>
<body>
<h1>点击按钮进行图片的切换</h1>
<div id="app">
<img src="/Users/macbookair/Desktop/picture/0.jpg" alt="">
<img src="/Users/macbookair/Desktop/picture/1.jpg" alt="">
<img src="/Users/macbookair/Desktop/picture/2.jpg" alt="">
<img src="/Users/macbookair/Desktop/picture/3.jpg" alt="">
<img src="/Users/macbookair/Desktop/picture/4.jpg" alt="">
<img src="/Users/macbookair/Desktop/picture/5.jpg" alt="">
</div>
<div id="but">
<button>下一张</button>
<button>上一张</button>
</div>
<!--
<script type="text/javascript">
//原生js实现
var ap1=document.getElementById('app').getElementsByTagName('img');
var but1=document.getElementById('but').getElementsByTagName('button');
var i=0;
ap1[i].className="choose";
but1[0].onclick=function() {
if( (i+1)==ap1.length ) {
alert("最后一张了!");
return;
}
ap1[i].className="";
ap1[++i].className="choose";
}
but1[1].onclick=function() {
if( i<=0 ) {
alert("第一张!");
return;
}
ap1[i].className="";
ap1[--i].className="choose";
}
</script>
-->
//jQuery实现
<script src="../jquery-1.12.3/jquery-1.12.3.min.js">
</script>
<script type="text/javascript">
var i=0;
var im=$('img');
im.eq(i).show(500);
$('button').eq(0).click(function() {
if ( (i+1)==im.size() ) {
alert("最后一张了");
return;
}
//jQuery fadeIn() 用于淡入已隐藏的元素
//jQuery fadeOut() 方法用于淡出可见元素。
im.eq(i++).fadeOut(500);//隐藏
im.eq(i).fadeIn(500);
});
$('button').eq(1).click(function() {
if ( i==0 ) {
alert("最后一张了");
return;
}
im.eq(i--).fadeOut(500);
im.eq(i).fadeIn(500);
});
</script>
</body>
</html>
<jQery-点击按钮图片切换两种实现>
最新推荐文章于 2024-06-12 16:47:41 发布