0

我正在编写一个脚本来查找 kind 的链接<a href='image_url'>...</a>,其中 image_url 是图像的 url,然后向这些标签添加一个onclick='popupImage(this)'属性,打开一个显示图像的弹出窗口。我知道如何查找这些标签,而我的问题是关于编写 popupImage 函数。到目前为止,我有

function popupImage(link){
    window.open(link,'image','width=400,height=400'); 
}

这很好用,但是一旦加载,我想调整弹出窗口的大小以适合图像。因此,我可能需要这种东西

function popupImage(link){
    w=window.open(link,'image','width=400,height=400');
    w.onload = function(){
        ... Do something to get the size of the image...
        ... Resize the popup (this, I know how to do)...
    }
}

但是我不知道如何访问窗口加载的图像,因为它没有 DOM ......问题是我真的不想在弹出窗口中写入一些 HTML 来显示图像(出于其他一些原因)。

任何建议将不胜感激。提前致谢!

4

2 回答 2

3

这是基于您更新的问题的解决方案

HTML

<a href="http://img145.imageshack.us/img145/1750/barcelonaagbartowernighnx7.jpg">One</a>
<a href="http://img515.imageshack.us/img515/5390/005cc0.jpg">Two</a>
<a href="http://imageshack.us/a/img708/9470/compatiblechrome.gif">Three</a>

Javascript

(function () {
    window.addEventListener("load", function onLoad() {
        this.removeEventListener("load", onLoad);

        Array.prototype.forEach.call(document.getElementsByTagName("a"), function (anchor) {
            anchor.addEventListener("click", function (evt) {
                evt.preventDefault();

                var newImg = document.createElement("img");

                newImg.src = anchor.href;
                newImg.addEventListener("load", function imgLoad() {
                    this.removeEventListener("load", imgLoad);

                    window.open(newImg.src, "image", "width=" + newImg.width + "px,height=" + newImg.height + "px");
                }, false);
            }, false);
        });
    }, false);
}());

jsfiddle 上

于 2013-05-12T21:59:05.267 回答
0

问题更新后不再是解决方案。

这是一个可能的解决方案

CSS

.image {
    width: 50px;
    height: auto;
}

HTML

<img class="image" src="http://img145.imageshack.us/img145/1750/barcelonaagbartowernighnx7.jpg" />
<img class="image" src="http://img515.imageshack.us/img515/5390/005cc0.jpg" />
<img class="image" src="http://imageshack.us/a/img708/9470/compatiblechrome.gif" />

Javascript

(function (global) {
    global.addEventListener("load", function onLoad() {
        global.removeEventListener("load", onLoad);

        Array.prototype.forEach.call(document.getElementsByTagName("img"), function (image) {
            var newImg = document.createElement("img");

            newImg.src = image.src;
            image.addEventListener("click", function () {
                global.open(image.src, "image", "width=" + newImg.width + "px,height=" + newImg.height + "px");
            }, false);
        });
    }, false);
}(window));

jsfiddle 上

于 2013-05-12T21:09:51.717 回答