使用jQuery获得元素大小的几率为50/50

时间:2012-07-24 13:11:25

标签: jquery image window image-size

我有一些奇怪的问题,我觉得很难在jsfiddle上重现。我能做的最好的是this,但每次打印出正确的宽度和高度时都能正常工作。

同时它的效果只有50%。其他时候它的图像大小和宽度为0。

我的HTML是:

<div role="main" id="main">
<div class="row">
    <div class="twelve columns" style="float:none;">
            <img src="/media/files/clientfiles/test1_X-1a_.png" id="editorImage">
    </div>
    <div class="four columns">zalalal</div>
</div>
</div>

匹配css是:

#main {
width: 1000px;
margin: 50px auto;
background: white;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-moz-box-shadow: 0px 0px 5px rgba(0,0,0,0.23);
-webkit-box-shadow: 0px 0px 5px rgba(0,0,0,0.23);
box-shadow: 0px 0px 5px rgba(0,0,0,0.23);
color: #666;}

.row {
width: 1000px;
max-width: 100%;
min-width: 768px;
margin: 0 auto;
}

.row .twelve {
width: 75%;
}

.column, .columns {
float: left;
min-height: 1px;
padding: 0 10px;
position: relative;
}

和javascript是

jQuery(function($){
        var element = $('#editorImage');
        console.log(element);
        console.log(element.width());
        console.log(element.height());
        console.log(element.outerWidth());
        console.log(element.outerHeight());
        console.log(element.offsetWidth);
        console.log(element.offsetHeight);
});

起初我认为它与在文档准备好之前尝试获取元素大小有关,但是jQuery(function($...应该处理它,不是吗?

3 个答案:

答案 0 :(得分:4)

您应该抓住window.load,而不是document.ready

后者等待DOM树准备就绪,但如果你想等待加载所有图像,前者也是必要的。

$(function() {
    // do DOM ready related stuff here
});

$(window).on('load', function() {
    // do image related stuff here
});

答案 1 :(得分:1)

你确定图像已加载吗?

尝试在$(window).load(function)之后获取尺寸;或$(img).load(function);

答案 2 :(得分:1)

其他人建议使用$(window).load,但我建议可能使用其他选项。

由于您可能希望在加载特定图像后立即设置样式,例如假设您加载了100个图像,并且每行样式仅依赖于一个图像,您不希望等待加载所有图像。

您可以在图像上使用.load功能,但是必须要小心,因为如果图像存储在缓存中,某些浏览器将不会调用此函数,因此我将函数拆分如下,如果需要你可以传递参数,虽然我的例子我会把它们留下来。

function imageLoadedFunction() {
    //some code to execute once the image has loaded
    //(you could pass a reference to the image in the function)
}

$(document).ready(function() {
    $image = $('#imageId');
    if($image.width() != 0)
        imageLoadedFunction();
});

$('#imageId').load(function() {
    imageLoadedFunction();
});

这确保了如果图像没有被缓存,则在图像加载完成后将调用load()函数,如果图像被缓存,则将从文档中调用该函数。