【问题标题】:Jquery .width() returns 0 zero before appending the image to the browserJquery .width() 在将图像附加到浏览器之前返回 0 零
【发布时间】:2013-08-08 14:19:05
【问题描述】:

我正在使用 jquery,我正在尝试创建幻灯片。

在添加图片之前,我应该知道图片的宽度。 所以我使用 .width() 的 jquery 和 .attr("width").

我的代码如下:

var attr_href = $next.attr('href'); /*returns the href of the image*/
var $item = $('<img src="'+attr_href+'" />'); 

//$item contains the image, the image is not displayed to the browser yet!!!

var itemWidth = $item.width();
alert(itemWidth); 
// --->  returns zero 0 in Mozilla and in IE

var itemWidth2 = $item.attr("width");
alert(itemWidth2);
//In Mozilla, the first time it returns 0.After the image is loaded, it returns the right Width
//In IE, always returns 0 zero !!!

//Now i have to append the photo and i have to use the right Width of the image!!!
var final_img = $('<img src="'+attr_href+'" width="'+itemWidth+'"/>');
$('.SlideShow').append(final_img);

所以,我尝试使用 .load() 并且我做到了:

var attr_href = $next.attr('href'); /*returns the href of the image*/
var $item = $('<img src="'+attr_href+'" />'); 

//$item contains the image, the image is not displayed to the browser yet!!!

$item.load(function  () {
    var WidthAfterLoading = $item.attr("width");
    var WidthAfterLoading2 = $item.width();

});

alert(WidthAfterLoading);  //returns "undefined" in both IE and Mozilla
alert(WidthAfterLoading2); //returns "undefined" in both IE and Mozilla

所以,在我将图像附加到浏览器之前,我应该知道图像的正确宽度。 但我得到零(0)和未定义。

有没有其他方法,为了取图片的正确宽度?

谢谢,提前

【问题讨论】:

  • 没有width属性
  • 抱歉,我以为$itema 标签。

标签: javascript jquery width


【解决方案1】:

啊,我之前也遇到过同样的问题。

<img id="someImage"></img>

然后在你的 JQuery 中

$("#someImage").attr("src", "url/to/img").load(function() {  
    var width = $(this).width();
    // do stuff!
});

当然还有fiddle

【讨论】:

  • 谢谢,我还是得到 0 零。即使加载图像,我又得到零。我不知道我该怎么办......
  • 在小提琴上试用您的代码并将其粘贴到此处,以便我们看看发生了什么:)
【解决方案2】:

这是因为元素没有附加到 DOM 树
在调用 .width() 之前尝试将元素附加到 DOM

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2011-03-13
    • 2013-04-14
    相关资源
    最近更新 更多