html代码如下:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META charset="utf-8">
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/javascript.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</HEAD>
<BODY>
<div id="main">
<h2>
图片循环展示
<h2>
<a class="showit" href="images/1.jpg">
<img src="images/small/1.jpg"/>
</a>
<a class="showit" href="images/2.jpg">
<img src="images/small/2.jpg"/>
</a>
<a class="showit" href="images/3.jpg">
<img src="images/small/3.jpg"/>
</a>
<a class="showit" href="images/4.jpg">
<img src="images/small/4.jpg"/>
</a>
<a class="showit" href="images/5.jpg">
<img src="images/small/5.jpg"/>
</a>
<a class="showit" href="images/6.jpg">
<img src="images/small/6.jpg"/>
</a>
</div>
</BODY>
</HTML>
style.css如下:
body{
background-color: #efefef;
}
#main{
border: solid 1px red;
background-color: #fff;
max-width: 600px;
padding: 20px;
margin: 20xp auto;
}
.showit{
text-decoration: none;
}
#showbox {
position: absolute;
top: 0;
left: 0;
background-color: #000;
width: 100%;
height: 100%;
text-align: center;
}
#showbox img {
max-width: 800px;
margin-top: 200px;
box-shadow: 0 0 20px #fff;
border-radius: 10px;
}
js如下:
$(function() {
$('.showit').click(function(event) {
var largeImageUrl = $(this).attr('href');
var boxEl = $('#showbox');
if(!boxEl.length) {
boxEl = $('<div>', {
id: 'showbox',
html: '<img/>'
}).appendTo(document.body);
}
boxEl.find('img').attr('src', largeImageUrl);
boxEl.show();
event.preventDefault();
});
var cachedImageUrls;
function cacheImageUrls() {
if(!cachedImageUrls) {
cachedImageUrls = $('.showit').map(function() {
return $(this).attr('href');
});
}
}
function getNextImageUrl(imageUrl) {
cacheImageUrls();
var imageUrlIndex = $.inArray(imageUrl, cachedImageUrls);
if(imageUrlIndex >= 0) {
imageUrlIndex++;
if(imageUrlIndex >= cachedImageUrls.length) {
imageUrlIndex = 0;
}
return cachedImageUrls[imageUrlIndex];
}
}
function getPrevImageUrl(imageUrl) {
cacheImageUrls();
var imageUrlIndex = $.inArray(imageUrl, cachedImageUrls);
if(imageUrlIndex >= 0) {
imageUrlIndex--;
if(imageUrlIndex < 0) {
imageUrlIndex = cachedImageUrls.length - 1;
}
return cachedImageUrls[imageUrlIndex];
}
}
$(document.body).on('click', '#showbox', function(event) {
var targetEl = $(event.target);
if(targetEl.is('img')) {
var imageLeft = targetEl.offset().left;
var imageHalfX = imageLeft + targetEl.outerWidth() / 2;
var imageUrl = targetEl.attr('src');
var nextImageUrl;
if(event.pageX > imageHalfX) {
nextImageUrl = getNextImageUrl(imageUrl);
} else {
nextImageUrl = getPrevImageUrl(imageUrl);
}
if(nextImageUrl) {
targetEl.attr('src', nextImageUrl);
}
} else {
$(this).hide();
}
});
});
![]()