0

这就是我所拥有的

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '')
var tempImg = '<img id="tempImg" src="' + path + ' "/>';
$('body').append(tempImg); 
alert($('#tempImg').width());

结果是0,但是如果我进入控制台并输入$('#tempImg').width(),我们会得到正确的宽度。

那么,看起来附加只是在执行代码后“加载”,我需要在附加项目后使用我的代码,有没有办法?

4

2 回答 2

0

您必须等到图像加载完毕。

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = new Image();
tempImg.id = "tempImg";
$(tempImg).load(function(){
    $('body').append(tempImg);
    alert($(tempImg).width());
});
tempImg.src = path;
于 2012-08-02T19:05:36.990 回答
0

感谢这里的一些评论和答案,我成功实现了我的目标

    frame_width = $('#sprite').width();

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '')
var tempImg = '<img id="tempImg" src="' + path + ' "/>';
    $('body').append(tempImg); 
    $('#tempImg').load(function(){
        alert($("#tempImg").width());
    });

这有效并提醒了正确的价值谢谢大家

于 2012-08-02T19:35:39.600 回答