获取隐藏图像的高度?

时间:2012-11-06 15:07:49

标签: jquery image hidden image-size

所以我已经为同一个问题阅读了许多其他解决方案,但它们似乎都没有用。

我有一堆图像,其中大部分都是在页面加载时隐藏的。只有第一张图像可见。我需要做的是给它们一个负的上边距,使图像垂直居中。唯一的问题是,我现在的代码是非常不一致,只是时不时地工作。我实际上不确定这是我的代码还是图像被缓存或其他什么。

这就是我所拥有的:

$('#frontpage-sidebar-slideshow img').each(function(i, v) {

    // I read that preloading the images would solve the problem, but this doesn't do anything
    //var src = $(this).attr('src');
    //$('<img/>')[0].src = src;

    // First make parent .slide visible to be able to get the image dimentions (not possible if image is invisible)
    var showAfter = false;
    if(!$(this).parent('.slide').is(':visible')) {
        showAfter = true;
        $(this).parent('.slide').css({ // .show() might also work
            display: 'block',
            visibility: 'visible',
            opacity: 1
        });
    }

    // Get dimentions
    var wrapHeight = parseInt($('#frontpage-sidebar-slideshow').height(), 10) + 20;
    var imgHeight = $(this).height();
    var offset = Math.ceil((wrapHeight - imgHeight) / 2);

    // Set offset if needed
    if(imgHeight > wrapHeight) {
        $(this).css('margin-top', offset);
    }

    // Show image again if needed
    if(showAfter) {
        $(this).parent('.slide').show();
    }
});

我正在使用SlidesJS创建图像的幻灯片。 HTML格式如下所示:

   <div class="slide">
    <a href="url goes here">
        <img width="200" src="image src goes here" alt="" style="">
        <div class="overlay">
            <p class="title"> Some title </p>
            <p> Some content </p>
            <p> More content </p>
        </div> <!-- overlay -->
    </a>
    </div>
   <div class="slide" style="display: none;"> <!-- Only the first image is visible, so this one will be hidden -->
    <a href="url goes here">
        <img width="200" src="image src goes here" alt="" style="">
        <div class="overlay">
            <p class="title"> Some title </p>
            <p> Some content </p>
            <p> More content </p>
        </div> <!-- overlay -->
    </a>
    </div>

有两个问题:

1)第一张图片的高度结果非常不一致。有时我得到包装器值(.slide的高度),有时我得到实际的高度值。我不知道造成这种情况的原因。

2)无论我做什么,我只得到第一张图片的高度值。其余图片只返回0。是的,他们甚至没有返回奇怪的包装高度(.slide的高度)。

有什么想法吗?

更新我刚刚意识到SlidesJS和我的脚本都在页面加载上运行,它们可能会发生碰撞(我试图显示图像,获取它们的大小,然后隐藏它们,而SlidesJS想要隐藏所有这些除了第一个),所以我尝试将整个脚本包装在setTimeout(code, 300)中,现在它至少似乎给了我第一张图像的一致结果,但其余的图像仍然返回0

1 个答案:

答案 0 :(得分:8)

您可以检查DOM之外的图像:

var tmp = new Image()
tmp.src="http://i.imgur.com/vdDQgb.jpg" <-- set to the image path you're using.
alert(tmp.height)

要确保图像已加载,请在指定SRC之前挂接onload事件。

var tmp = new Image()
tmp.onload=function() {alert(tmp.height)};
tmp.src="http://i.imgur.com/vdDQgb.jpg";