js 自定义事件 document.createEvent

小demo 图片查看器

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片查看器</title>
<style>
ul{
list-style: none;
display: flex;
flex-wrap: wrap;
}
ul img{
width: 400px;
}
#mask{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color:rgba(1,1,1,0.5);
text-align: center;
}
.preview{
display: inline-block;
color: white;
font-size: 300%;
float: left;
margin-top: 50vh;
}
.next{
display: inline-block;
color: white;
font-size: 300%;
float: right;
margin-top: 50vh;
}
</style>
</head>
<body>
<ul id="list">
<li><img src="1-1.jpg" alt=""></li>
<li><img src="1-2.jpg" alt=""></li>
<li><img src="1-3.jpg" alt=""></li>
<li><img src="1-4.jpg" alt=""></li>
<li><img src="1-5.jpg" alt=""></li>
</ul>
<div id="mask">
<span class="preview">< </span>
<img src="" alt="">
<span class="next">></span>
</div>
</body>
<script>
const imgList = document.getElementById('list');
let imgs = document.querySelectorAll('ul img');
function setPreviewBehavior(subjects) {
let previewEvent = document.createEvent('Event');
previewEvent.initEvent('preview',true,true);
if(!Array.isArray(subjects)){
if(subjects.length) subjects = Array.from(subjects);
else subjects = [subjects];
}
previewEvent.previewTarget = subjects.map(evt => {
return evt.src;
});
subjects.forEach(subject => {
subject.preview = function () {
subject.dispatchEvent(previewEvent);
}
});
}
setPreviewBehavior(imgs);
const previewMask = document.getElementById('mask');
let previewImage = previewMask.querySelector('img');
let previewPrevious = previewMask.querySelector('.preview');
let previewNext = previewMask.querySelector('.next');
previewMask.addEventListener('click',evt => {
if(evt.target === previewMask){
evt.target.style.display= 'none';
}
});
imgList.addEventListener('click',evt => {
if (evt.target.preview) {
evt.target.preview();
}
});
imgList.addEventListener('preview', evt => {
const src = evt.target.src,
imgs = evt.previewTarget;
previewMask.style.display = 'block';
previewImage.src = src;
let idx = imgs.indexOf(src);
function updateButton(idx) {
previewPrevious.style.display = idx ? 'block': 'none';
previewNext.style.display= idx < imgs.length-1 ? 'block' : 'none';
}
updateButton(idx);
previewPrevious.onclick = function (evt) {
previewImage.src = imgs[--idx];
updateButton(idx);
};
previewNext.onclick = function (evt) {
previewImage.src = imgs[++idx];
updateButton(idx);
}
})
</script>
</html>
posted @ 2017-12-12 15:23  情绪控攻城狮  阅读(1739)  评论(0编辑  收藏  举报