3

我在一个页面上有一堆图像。我正在尝试使用 jQuery 来获取每个图像的高度并将其显示在图像之后。所以这是我的代码:



$(document).ready(function() {
  $(".thumb").each(function() {
    imageWidth = $(".thumb img").attr("width");
    $(this).after(imageWidth);
  });
});

<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>

[...]


我在 jQuery 背后的逻辑是我想遍历每个“thumb”选择器,将“thumb”内的 img 高度分配给变量“imageWidth”,然后在每个“thumb”之后以文本显示高度。

我遇到的问题是它只在第一张图像上工作,然后退出。当然,如果我使用“thumb_img”类,我可以让它工作,但我需要访问“thumb”类的图像高度。

希望这不会太令人困惑,因为我对 jQuery 还很陌生。提前谢谢。

4

4 回答 4

10

您将无法使用 document.ready() 来执行此操作,因为在调用时图像尚未加载。

您实际上需要将此代码放入 onload() 事件处理程序中,该处理程序在文档和所有图像完成加载后调用。

只有当图像完成加载时,浏览器才知道它们有多大。

于 2009-08-13T18:56:22.127 回答
9

用这个:

imageWidth = $(this).children("img").attr("width")

以下选择所有图像:

$(".thumb img")

...因此,当您要求属性时,它会从集合中的第一个对象返回它

对不起所有的编辑......但最好重用 jquery 对象,所以:

var $this = $(this)

然后参考 $this 进行优化。在这个例子中没什么大不了的,但这是一个很好的使用习惯。

于 2009-08-13T18:50:49.520 回答
0
$().ready(function() {

        $(".thumb img").load(function() {
            var imageHeight = $(this).height();
            $(this).parent().append(imageHeight);

        });

});
于 2009-08-13T19:29:30.970 回答
0

我使用了类似的东西来预加载图像并在 mouseover 和 mouseout 中设置一些代码,并为所有具有类名“swap”的图像设置样式。对我来说$(this)没有工作但直接this工作:

// in jquery
$(document).ready(function(){
        swapAndPreload();
    });

function swapAndPreload(){
    $(".swap").each(function(){
        // preload images in cache
        var img = new Image();
        img.src=this.src.replace(/([-_])out/,'$1over');
        //set the hover behaviour
        this.onmouseover = function(){
            this.src=this.src.replace(/([-_])out/,'$1over');
        }
        //set the out behaviour
        this.onmouseout = function(){
            this.src=this.src.replace(/([-_])over/,'$1out');
        }
        //set the cursor style
        this.style.cursor="pointer";
    });
}
于 2011-03-07T20:22:05.730 回答