Javascript 将图像附加到浏览器之前,Jquery.width()返回0
我正在使用jquery并尝试创建幻灯片 在附加图像之前,我应该知道图像的宽度。 所以我使用jquery的.width和.attrwidth 我的代码如下:Javascript 将图像附加到浏览器之前,Jquery.width()返回0,javascript,jquery,width,Javascript,Jquery,Width,我正在使用jquery并尝试创建幻灯片 在附加图像之前,我应该知道图像的宽度。 所以我使用jquery的.width和.attrwidth 我的代码如下: 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 dis
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
因此,在我将图像附加到浏览器之前,我应该知道图像的正确宽度。
但我得到了零和未定义
为了获得正确的图像宽度,还有其他方法吗
谢谢,事先啊,我以前也有同样的问题
<img id="someImage"></img>
当然还有一个 啊,我以前也有同样的问题
<img id="someImage"></img>
当然还有一个 这是因为元素没有附加到DOM树
在调用之前尝试将元素附加到DOM。这是因为元素没有附加到DOM树
在调用之前尝试将元素附加到DOM。width没有width Attribute I抱歉,我认为$item是a标记。没有width Attribute I抱歉,我认为$item是a标记。谢谢,我仍然得到0。即使在加载图像时,我再次得到零。我不知道我该怎么做…在小提琴上试用你的代码,然后粘贴到这里,这样我们就可以看看发生了什么:谢谢,我仍然得到零。即使在加载图像时,我再次得到零。我不知道我该怎么做…在小提琴上试用你的代码,然后粘贴到这里,这样我们就可以看看发生了什么: