js 自定义事件 document.createEvent

Posted 情绪控攻城狮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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" ></li>
<li><img src="1-2.jpg" ></li>
<li><img src="1-3.jpg" ></li>
<li><img src="1-4.jpg" ></li>
<li><img src="1-5.jpg" ></li>
</ul>
<div id="mask">
<span class="preview">< </span>
<img src="" >
<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>












































































































以上是关于js 自定义事件 document.createEvent的主要内容,如果未能解决你的问题,请参考以下文章

tips 原生js

js事件自定义dom事件自定义事件

js怎么自定义事件,并能让用on事件监听

js自定义事件DOM/伪DOM自定义事件

js-自定义事件

怎样让前端界面自动清理js,css文件的缓存