也许有人仍在寻找解决方案。
我在我的项目中遇到了同样的问题。不适用于 youtube iframe,但实现它并不难。Lightbox2 无法扩展,所以我编写了添加监听器和观察器的简单类。为了正确显示,要求视频具有相同尺寸的海报。这是保持弹出窗口大小正确的最快方法。
在 href 中需要添加带有图像 url 的数据集 href
<a href="POSTER_URL" data-href="VIDEO_URL" data-lightbox="Videos">
Open Lightbox
</a>
SCSS 在弹出窗口中覆盖图像并在加载时设置淡入淡出效果
.lightbox {
.lb {
&-outerContainer {
video {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 9999;
width: 100%;
height: auto;
opacity: 1;
transition: opacity 300ms ease-in-out;
border: none;
outline: none;
&:hover, &:focus {
border: none;
outline: none;
}
}
&.animating {
video {
opacity: 0;
}
}
}
&-container {
position: relative;
.lb-image {
border: none;
}
}
}
}
以及创建视频并将视频设置为弹出窗口的 JS 类。也许有点乱,但我不在乎。这只是快速的解决方案。
class LightBoxVideo {
constructor() {
this.videos = {};
this.lightBoxVideo();
}
lightBoxVideo = () => {
this.setEvents();
this.setMutationObserver();
}
setMutationObserver = () => {
const observer = new MutationObserver(mutation => {
const imageMutations = mutation.filter((m) => {
return m.attributeName === "src" && m.target.className === 'lb-image'
});
const overlayDisplay = window.getComputedStyle(document.querySelector('.lightboxOverlay'), null).display;
if("none" === overlayDisplay) {
this.removeVideoElement();
}
if(imageMutations.length > 0) {
if(this.videos[imageMutations[0].target.src]) {
this.removeVideoElement();
this.setVideoElement(this.videos[imageMutations[0].target.src]);
}
}
});
observer.observe(document.body, {
childList: false,
attributes: true,
subtree: true,
characterData: false
});
}
setEvents = () => {
const videoLinks = this.findVideoLinks();
videoLinks.forEach((link) => {
this.videos[link.href] = link;
link.addEventListener('click', (e) => {
this.removeVideoElement();
this.setVideoElement(e.target);
});
});
}
setVideoElement = (element) => {
const lightbox = document.querySelector('.lightbox')
const container = lightbox.querySelector('.lb-container');
const videoElement = this.createVideoElement(element);
container.prepend(videoElement);
}
removeVideoElement = () => {
const lightbox = document.querySelector('.lightbox')
const container = lightbox.querySelector('.lb-container');
const video = container.querySelector('video');
if(video) {
container.removeChild(video);
}
}
createVideoElement = (element) => {
const video = document.createElement('video');
video.setAttribute('poster', element.href);
video.setAttribute('controls', 'true');
const source = document.createElement('source');
source.setAttribute('src', element.dataset.href);
source.setAttribute('type', 'video/mp4');
video.append(source);
return video;
}
findVideoLinks = () => {
const hrefs = document.querySelectorAll('a[data-lightbox]');
const regex = /\.(mp4|mov|flv|wmv)$/;
if(0 === hrefs.length) {
return [];
}
return Array.from(hrefs).filter((href) => {
return !! href.dataset.href.match(regex);
});
}
}
要预览它是如何工作的 - 此处为 codepen:https ://codepen.io/PatrykN/pen/RwKpwMe