有個(gè)需求,要求將iframe中的圖片在當(dāng)前窗口居中打開,要求:
1、不能依賴父頁面提供相關(guān)方法;
2、打開后圖片以外的部分不能是黑底,可以透明或半透明;
方案:
- 方案1:
| 方案 | 弊端 |
|---|---|
| 通過js將相關(guān)圖片插入body,并通過設(shè)置樣式(例如display: fixed),使其居中展示 | 無法突破iframe,在整個(gè)窗口居中顯示 |
通過requestFullscreen方法,將圖片或圖片容器打開 |
背景色無法設(shè)置為透明 |
通過window.open方法打開一個(gè)窗口,控制窗口位置和大小來實(shí)現(xiàn)居中展示,具體代碼邏輯如下 |
無法去掉小窗口的地址欄 |
let openedWindow = null;
function showImgByOpener() {
// 事件委托,監(jiān)聽所有圖片點(diǎn)擊
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;
// 計(jì)算新窗口的最佳位置
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, '圖片預(yù)覽', windowSpecs);
openedWindow = window.open('', '圖片預(yù)覽', windowSpecs);
openedWindow.document.write(`<html><head><title>${target.name}圖片預(yù)覽</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();