首先引入jQuery文件和JS文件
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="js/docview.js"></script>
HTML代码
<div id="content">
<h1>动态JS网页浏览器</h1>
<p>点击下面图像自动跳转到下一个文件。或者按左←,右→切换.</p>
<div id="controls">
<a href="#" id="backpage">←</a>
<a href="#" id="forwardpage">→</a>
</div>
<div id="documentcontainer">
<img src="images/01.jpg" data-page="1">
</div>
</div>
我只用→和←用于显示箭头的链接。重要的是箭头链接的ID。这些对应于用户点击任一箭头后,向前或向后移动文档集的触发jQuery的事件处理程序。
CSS代码
#documentcontainer {
display: block;
width: 100%;
padding-top: 22px;
margin-bottom: 10px;
}
#documentcontainer img {
display: block;
margin: 0 auto;
border: 0;
cursor: pointer;
}
#controls {
display: block;
padding: 0 35px;
text-align: center;
}
#controls a {
font-size: 3.6em;
font-weight: bold;
}
#controls a:hover {
text-decoration: none;
color: #72ad69;
}
#controls a#backpage {
margin-right: 20px;
}
JS代码
这里我们命名为docview.js
var setDirectory = "images/"; // 当前documentset目录,包括结尾的斜线
var fileTypes = "jpg"; // 图片文件类型, 通常是jpg 或者 png
var lastDocNum = 4; // 设定最后文件的编号
var fileDigits = 2; // 文件名前的数字总数: 01, 001, 0001
function addLeadingZeros (n, length) {
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
zeros += '.'+fileTypes;
return n >= 0 ? zeros : "-" + zeros;
}
/* begin jQuery */
$(function(){
var docimage = $('#documentcontainer > img');
$(docimage).on('click', function(e){
e.preventDefault();
var currentid = $(this).attr('data-page');
var newimgid = parseInt(currentid)+1;
var newimgsrc = setDirectory;
if(currentid == lastDocNum) {
// if viewing the last page then do nothing
return false;
}
newimgsrc += addLeadingZeros(newimgid, fileDigits);
$(this).attr('data-page', newimgid);
$(this).attr('src', newimgsrc);
}); // event handler for clicking doc image
$('#controls > #forwardpage, #controls > #backpage').on('click', function(e){
e.preventDefault();
var currentid = $(docimage).attr('data-page');
var newimgsrc = setDirectory;
if($(this).attr('id') == 'backpage')
var newimgid = parseInt(currentid)-1;
else if($(this).attr('id') == 'forwardpage')
var newimgid = parseInt(currentid)+1;
if(currentid == lastDocNum && $(this).attr('id') == 'forwardpage') {
// if viewing the last page then no more forward links
return false;
}
if(currentid == 1 && $(this).attr('id') == 'backpage') {
// if viewing the first page then no going backwards
return false;
}
newimgsrc += addLeadingZeros(newimgid, fileDigits);
$(docimage).attr('data-page', newimgid);
$(docimage).attr('src', newimgsrc);
}); // event handler for clicking arrow links
});
Web前端(W3Cways.com) - Web前端学习之路