开发者

change img src and width

I change the开发者_开发百科 scr of an img tag using jQuery, such as,

$("#img1").attr("src", "pic1.png");

after this, I try to get the width of img (it's not set in html),

$("#img1").width();

it seems the width is not changed with the src, did I miss something? thanks.


If you're trying to do it immediately, it may be because the image isn't fully loaded yet.

Add a single load handler to the image using .one().

$("#img1").attr("src", "pic1.png").one('load',function() {
    alert($(this).width());
});

or in case the image was cached, you can try this:

$("#img1").attr("src", "pic1.png").each(function() {
    if( this.complete ) {
        alert($(this).width());
    } else {
        $(this).one('load',function() {
            alert($(this).width());
        });
    }
});

As noted by @Humberto, you were using scr instead of the proper src.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜