pro*_*mer 1 javascript jquery width
我正在使用jquery,我正在尝试创建幻灯片.
在我附加图像之前,我将知道图像的宽度.所以我使用jquery和.attr("width")的.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);
Run Code Online (Sandbox Code Playgroud)
所以,我试图使用.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
Run Code Online (Sandbox Code Playgroud)
所以,在我将图像附加到浏览器之前,我将知道图像的正确宽度.但我得到零(0)和未定义.
还有其他方法,为了采取正确的图像宽度??
提前致谢
啊,我之前遇到过同样的问题.
<img id="someImage"></img>
Run Code Online (Sandbox Code Playgroud)
然后在你的JQuery中
$("#someImage").attr("src", "url/to/img").load(function() {
var width = $(this).width();
// do stuff!
});
Run Code Online (Sandbox Code Playgroud)
当然还有小提琴!
| 归档时间: |
|
| 查看次数: |
2128 次 |
| 最近记录: |