基本的使用可以查看demo和文檔
https://github.com/fengyuanchen/viewerjs
https://fengyuanchen.github.io/viewerjs/
這裏只說我使用過程中遇到的兩個問題
1.動態加載的圖片無法查看
針對這個問題,可以使用update()方法來更新,將新加載的圖片放到viewer實例中,注意是在新的標籤寫到頁面後調用。
2.限制哪些圖片可以通過viewer.js查看
項目中我們也常遇見只需要部分圖片是需要被查看,比如,做一個聊天室,那麼用戶頭像肯定是不需要被查看的,我們只需要能查看好友雙方發送的圖片即可,這時就可以使用filter函數來過濾出來需要顯示的圖片,注意需要顯示的圖片,應該返回true。
以下爲改過的官方demo,可供演示查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Viewer.js</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="viewer.css">
<style>
.pictures {
list-style: none;
margin: 0;
max-width: 30rem;
padding: 0;
}
.pictures > li {
border: 1px solid transparent;
float: left;
height: calc(100% / 3);
margin: 0 -1px -1px 0;
overflow: hidden;
width: calc(100% / 3);
}
.pictures > li > img {
cursor: zoom-in;
width: 100%;
}
.viewer-download {
color: #fff;
font-family: FontAwesome, serif;
font-size: 0.75rem;
line-height: 1.5rem;
text-align: center;
}
.viewer-download::before {
content: "\f019";
}
</style>
</head>
<body>
<div class="container">
<h1 onclick="add()">點擊新增圖片</h1>
<div id="galley">
<ul class="pictures">
<li><img data-original="./img/tibet-1.jpg" src="./img/tibet-1.jpg" alt="Cuo Na Lake" class='img_show'></li>
<li><img data-original="./img/tibet-2.jpg" src="./img/tibet-2.jpg" alt="Tibetan Plateau" class=''></li>
<li><img data-original="./img/tibet-3.jpg" src="./img/tibet-3.jpg" alt="Potala Palace 2" class='img_show'></li>
<li><img data-original="./img/tibet-4.jpg" src="./img/tibet-4.jpg" alt="Potala Palace 3" class='img_show'></li>
</ul>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
<script src="viewer-1.4.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var galley = document.getElementById('galley');
viewer = new Viewer(galley, {
url: 'data-original',
toolbar: {
oneToOne: true,
prev: function() {
viewer.prev(true);
},
play: true,
next: function() {
viewer.next(true);
},
download: function() {
const a = document.createElement('a');
a.href = viewer.image.src;
a.download = viewer.image.alt;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
},
},
filter:function(img){
return $(img).hasClass('img_show');
}
});
});
function add(){
var html = '<li>'
+'<img data-original="./img/tibet-7.jpg" src="./img/tibet-7.jpg" class="img_show">'
+'</li>';
$(".pictures").append(html);
viewer.update(); //更新viewer實例
}
</script>
</body>
</html>