有个需求,要求将iframe中的图片在当前窗口居中打开,要求:
1、不能依赖父页面提供相关方法;
2、打开后图片以外的部分不能是黑底,可以透明或半透明;
方案:
- 方案1:
| 方案 | 弊端 |
|---|---|
| 通过js将相关图片插入body,并通过设置样式(例如display: fixed),使其居中展示 | 无法突破iframe,在整个窗口居中显示 |
通过requestFullscreen方法,将图片或图片容器打开 |
背景色无色设置为透明 |
通过window.open方法打开一个窗口,控制窗口位置和大小来实现居中展示,具体代码逻辑如下 |
无法去掉小窗口的地址栏 |
let openedWindow = null;
function showImgByOpener() {
// 事件委托,监听所有图片点击
document.addEventListener('click', async (e) => {
const target = e.target;
if (target.tagName.toLowerCase() !== 'img') {
if (openedWindow && !openedWindow.closed) {
openedWindow.close();
openedWindow = null;
}
return;
};
e.preventDefault(); // 禁止图片拖拽
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
// 定义新窗口尺寸
const windowWidth = 600;
const windowHeight = 400;
// 计算新窗口的最佳位置
const left = (screenWidth - windowWidth) / 2; // 居中
const top = (screenHeight - windowHeight) / 2;
const windowSpecs = `popup,width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=no,resizable=no,location=no,menubar=no`;
//const newWindow = window.open(target.src, '图片预览', windowSpecs);
openedWindow = window.open('', '图片预览', windowSpecs);
openedWindow.document.write(`<html><head><title>${target.name}图片预览</title></head><body>`);
openedWindow.document.write(`<img src="${target.src}" width=${windowWidth - 20} height=${windowHeight - 20} alt="Image from iframe">`);
openedWindow.document.write('</body></html>');
openedWindow.document.close()
});
}
showImgByOpener();