javascript - Jquery .width() 在将图像附加到浏览器之前返回 0 零

标签 javascript jquery width

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

在附加图像之前,我应该知道图像的宽度。 所以我使用 jquery 的 .width().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)和未定义。

是否有任何其他方法,以获取图像的正确宽度??

提前致谢

最佳答案

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

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

然后在你的 JQuery 中

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

还有一个 fiddle当然!

关于javascript - Jquery .width() 在将图像附加到浏览器之前返回 0 零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668217/

相关文章:

javascript - 如何检查是否在文本区域中用 'enter' 键按下了 'shift' 键

css - 设置 span 元素的百分比宽度

javascript - 设置 img src 属性时宽度和高度不变

javascript - 如何在没有门户的情况下更改 Azure Web 应用程序中的启动命令?

javascript - 仅允许字母数字和特殊字符的正则表达式不起作用

javascript - 将虚拟键盘创建为 AngularJs 模块?

javascript - jquery 字符串值没有传递到循环内的谷歌地图对象

javascript - Mongoose 子文档 : cannot call method call to of undefined

javascript - 通过选择下拉菜单和按钮单击来隐藏/显示 div

javascript - 显示大内容(宽度)的 Fancybox3