Files
chatroom/resources/js/chat-room/lightbox.js
T

99 lines
2.7 KiB
JavaScript

// 聊天室图片预览层控制,迁出 Blade 内联脚本后通过事件委托接管打开和关闭。
let lightboxEventsBound = false;
/**
* 打开聊天图片大图预览层。
*
* @param {string} imageUrl 图片地址
* @param {string} imageName 图片名称
* @returns {void}
*/
export function openChatImageLightbox(imageUrl, imageName = "聊天图片") {
const lightbox = document.getElementById("chat-image-lightbox");
const imageEl = document.getElementById("chat-image-lightbox-img");
const nameEl = document.getElementById("chat-image-lightbox-name");
if (!lightbox || !imageEl || !imageUrl) {
return;
}
imageEl.src = imageUrl;
imageEl.alt = imageName;
if (nameEl) {
nameEl.textContent = imageName;
}
lightbox.style.display = "block";
document.body.style.overflow = "hidden";
}
/**
* 关闭聊天图片大图预览层。
*
* @param {Event|null} event 点击事件
* @returns {void}
*/
export function closeChatImageLightbox(event = null) {
// 遮罩点击才能关闭;点击预览图本身时保持打开,避免误关。
if (event && event.target !== event.currentTarget) {
return;
}
const lightbox = document.getElementById("chat-image-lightbox");
if (!lightbox) {
return;
}
lightbox.style.display = "none";
const imageEl = document.getElementById("chat-image-lightbox-img");
if (imageEl) {
imageEl.src = "";
}
document.body.style.overflow = "";
}
/**
* 绑定聊天图片预览层事件委托。
*
* @returns {void}
*/
export function initChatImageLightboxEvents() {
if (lightboxEventsBound) {
return;
}
lightboxEventsBound = true;
document.addEventListener("click", (event) => {
if (!(event.target instanceof Element)) {
return;
}
const imagePreview = event.target.closest("[data-chat-image-lightbox-image]");
if (imagePreview) {
// 图片节点自己不触发关闭,关闭按钮和遮罩由其他分支处理。
return;
}
const opener = event.target.closest("[data-chat-image-lightbox-open]");
if (opener) {
event.preventDefault();
// data-full 优先使用原图地址,href 作为旧链接结构的兼容兜底。
openChatImageLightbox(opener.dataset.full || opener.href, opener.dataset.alt || "聊天图片");
return;
}
if (event.target.closest("[data-chat-image-lightbox-close]")) {
event.preventDefault();
closeChatImageLightbox();
}
});
}
if (typeof document !== "undefined") {
initChatImageLightboxEvents();
}