這么寫好像可以實現(xiàn)保持預(yù)加載兩張圖片
<!DOCTYPE html>
<html lang="en">
<head>
? <meta charset="UTF-8">
? <title>預(yù)加載之有序加載</title>
? <style>
? ? .box {
? ? ? text-align: center;
? ? }
? ? .btn {
? ? ? display: inline-block;
? ? ? height: 30px;
? ? ? line-height: 30px;
? ? ? border: 1px solid #ccc;
? ? ? background-color: #fff;
? ? ? padding: 0 10px;
? ? ? margin-right: 50px;
? ? ? color: #333;
? ? }
? ? .btn:hover {
? ? ? background-color: #eee;
? ? }
? ? a {
? ? ? text-decoration: none;
? ? }
? </style>
</head>
<body>
? <div class="box">
? ? <img src="http://45.34.137.202:8080/comicdata/12307/1/0.jpg" alt="pic" id="img" width="1200">
? ? <p>
? ? ? <a href="javascript:;" class="btn"?data-control='prev'>上一頁</a>
? ? ? <a href="javascript:;" class="btn"?data-control='next'>下一頁</a>
? ? </p>
? </div>
? <script src='../jquery/jquery-3.2.1.min.js'></script>
? <script>
? ? var imgs = [
? ? ? ? ? 'http://45.34.137.202:8080/comicdata/12307/1/0.jpg',
? ? ? ? ? 'http://45.34.137.202:8080/comicdata/12307/1/1.jpg',
? ? ? ? ? 'http://45.34.137.202:8080/comicdata/12307/1/2.jpg',
? ? ? ? ? 'http://45.34.137.202:8080/comicdata/12307/1/3.jpg',
? ? ? ? ? 'http://45.34.137.202:8080/comicdata/12307/1/4.jpg'
? ? ? ];
? ? ? var len = imgs.length,
? ? ? ? ? count = 0,
? ? ? ? ? index = 0; ?
? ? ? load();?
? ? ? //有序預(yù)加載
? ? ? function load() {
? ? ? ?var imgObj = new Image();
? ? ? ?$(imgObj).on('load error', function() { //load后觸發(fā)一個方法
? ? ? ? ?if(count >= len) {
? ? ? ? ? ?//所有圖片加載完畢
? ? ? ? ?} else {
? ? ? ? ? ?if(count <= index+2)
? ? ? ? ? ?load();
? ? ? ? ?}
? ? ? ? ?count++;
? ? ? ?});
? ? ? ?imgObj.src = imgs[count];?
? ? ? ?//將當前圖片的路徑賦值各給圖片對象的scr來開始預(yù)加載
? ? ? ?// console.log(count);
? ? ? };
? ? ? $('.btn').on('click', function(){
? ? ? if('prev'=== $(this).data('control')) {
? ? ? ? if(index == 0) {
? ? ? ? ? alert('已經(jīng)是第一張了')
? ? ? ? }
? ? ? ? index = Math.max(0, --index);
? ? ? }else {
? ? ? ? if(index == len-1) {
? ? ? ? ? alert('已經(jīng)是最后一張了')
? ? ? ? }
? ? ? ? index = Math.min(len-1, ++index);
? ? ? }
? ? ? document.title = (index + 1) + '/' + len;
? ? ? $('#img').attr('src', imgs[index]);
? ? ? //點擊按鈕顯示到index對應(yīng)的圖片
? ? ? count = count-2;
? ? ? load();
? ? }); ??
? </script>
</body>
</html>
2017-05-17
....<a>標簽忘記加class了吧 加上試試