使用Javascript在新窗口中弹出图像

时间:2012-07-16 14:42:25

标签: javascript jquery image popup

我有一个网页,其中点击了一个元素,并使用JQuery post函数从服务器获取图像,并且应该在一个新窗口中显示,该窗口将调整为图像大小。相关的Javascript函数如下(其中myImage是基本64格式的返回图像)。

function showPicture(label) {
        var newWindow = window.open("", label,"scrollbars=0, toolbar=0");
        $.post( 'picture-view', { labelname: label },
        function(myImage) {
            newWindow.document.write("<img src='data:image/png;base64," + myImage + "'/>");
            newWindow.resizeTo(newWindow.document.getElementsByTagName("img")[0].width,     newWindow.document.getElementsByTagName("img")[0].height+newWindow.outerHeight-newWindow.innerHeight);
            newWindow.focus(); 

        }
    );          
}

有三件事让我有问题。

  1. 图像被插入带有白色边框的新窗口,我无法弄清楚如何移除。

  2. 在调整窗口大小时,术语newWindow.outerHeight-newWindow.innerHeight应该考虑工具栏等,但两者都输出为零。

  3. 这最后一个真让我烦恼。如果我将行var newWindow = window.open("", label,"scrollbars=0, toolbar=0");放在从第4行开始的回调函数中,则新窗口创建得太小而且不会被resizeTo函数调整大小。

  4. 任何进一步阅读的建议或指示都会非常有帮助。

2 个答案:

答案 0 :(得分:1)

你正在使用jQuery,所以你可以简化这个A LOT,但是因为你已经使用了普通的JS,所以我只是继续使用它。

您应该等到图像加载后再打开新窗口,这样您就可以将图像大小设置为与图像相同,如下所示:

function showPicture(label) {
    $.post( 'picture-view', { labelname: label }, function(ImageSrc) {
       var myImage = new Image;
           myImage.src = "data:image/png;base64," + ImageSrc;
           myImage.style.border = 'none';
           myImage.style.outline = 'none';
           myImage.style.position = 'fixed';
           myImage.style.left = '0';
           myImage.style.top = '0';
           myImage.onload = function() {        
               var newWindow = window.open("", label,"scrollbars=0, toolbar=0, width="+myImage.width+", height="+myImage.height);
                   newWindow.document.write(myImage.outerHTML);
          }​
    });
}

这是一个FIDDLE,展示了它是如何完成的,只是在文件中添加了base64,因为我没有时间创建某种伪Ajax函数。

答案 1 :(得分:0)

您可以这样在新窗口中引用图像:

var img = $("img",newWindow.document)[0]; // Get my img elem

适应您的代码:

function showPicture(label) {
    var newWindow = window.open("", label,"scrollbars=0, toolbar=0");
    $.post( 'picture-view', { labelname: label },
    function(myImage) {
        newWindow.document.write("<body marginheight='0' marginwidth='0'><img src='data:image/png;base64," + myImage + "'/></body>");
        var img = $("img",newWindow.document)[0];
        newWindow.resizeTo($(img).width(), $(img).height());
        alert($(img).width()+","+$(img).height()); //Just to check values
        newWindow.focus(); 
    });          
}

我猜白色边框是由于身体边缘,所以我添加了

<body marginheight='0' marginwidth='0'>

in

newWindow.document.write

删除它们。

我在Firefox中进行了测试并且它可以工作,但有时会打开一个较小的窗口,可能是因为调整大小是在整个图像加载之前完成的。在这种情况下,您可以添加window.setTimeout以避免此问题。

相关问题