[英]How to center an image in a pop up window
當單擊按鈕時,我的網站會打開一個包含單個圖像的窗口。
除了最后一點,我已經完成了所有工作-如何在彈出窗口中居中顯示圖像?
我不是在問如何使新窗口居中,只是在問新窗口的內容。
var img = document.createElement("img");
img.src = cont.getAttribute("data-img");
img.style.boxShadow = "1px 1px 3px #333;"
//as per https://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/
img.style.position="absolute";
img.style.top= "50%";
img.style.left= "50%";
img.style.marginTop= Number((img.height/2) * - 1) + "px"; /* Half the height */
img.style.marginLeft= Number((img.width/2) * - 1) + "px"; /* Half the width */
showImage(img);
});
function showImage(imgEle) {
var w = imgEle.width + (10 / 100 * imgEle.width);
var h = imgEle.height+ (10 / 100 * imgEle.height);
var url=imgEle.getAttribute('src');
window.open(url,"Image Viewer",'width='+w+',height='+h+',resizable=1, titlebar=no, toolbar=no');
}
上面的工作方式是顯示新窗口,並且我的圖像是頁面中唯一的東西,但是圖像停留在左上方,我希望它居中。
我知道這種方法存在問題(彈出式窗口攔截器)。
根據Javascript的標記以及我顯然只使用Javascript的事實,我正在尋找JavaScript解決方案(不依賴於任何庫/框架)
function center(divid) {
$(divid).css("position","absolute");
$(divid).css("top", (($(window).height() - $(divid).outerHeight()) / 2) + $(window).scrollTop() + "px");
$(divid).css("left", (($(window).width() - $(divid).outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
使用方法:
center("#divid");
將此添加到您的樣式
img.style.display = "block";
img.style.margin = "0 auto";
使用您已有的資源:
function showImage(imgEle) {
var url=imgEle.src;
var w = imgEle.width + (10 / 100 * imgEle.width);
var h = imgEle.height+ (10 / 100 * imgEle.height);
imgEle.style.marginLeft = 50% - (w / 2);// Center horizontally
imgEle.style.marginTop = 50% - (h / 2); // Center vertically
imgEle.style.display = "block";
window.open(url,"Image Viewer",'width='+w+',height='+h+',resizable=1, titlebar=no, toolbar=no');
}
如果由於某些原因不起作用,請嘗試使用transform
居中技巧
// The modal that is the image's parent.
// Absolute or fixed works as well.
.box {
position: relative;
}
// The image inside the modal.
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
我們應該將樣式化的圖像元素導入彈出窗口,而不是在彈出窗口中加載圖像資源。
function showImg (imgURL) {
var imageElem = document.createElement('img');
imageElem.onload = function () {
// style this image element
// ...
// create popup window with certain dimensions
// ...
// import image element from current document into popup document body <<<<<<<<<
popupWindow.document.body.appendChild(popupWindow.document.importNode(imageElem));
};
// load image now
imageElem.src = imgURL;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.