Jquery在图像上获得零宽度

时间:2013-04-23 07:02:51

标签: javascript jquery

我遇到了jquery width();

的问题

Html标记:

<img height="300px" src="http://localhost/portfolio/wp-content/uploads/Alone.jpg" alt="Alone" title="Alone" />

Jquery的:

var slide_width = 0;
    $("#barely_slide article img").each(function(){
        console.dir($(this).width());
    });
    console.dir(slide_width);

查看$(this)我看到clientWidth返回正确的值,也是offsetWidth,但是它们没有等效的jquery函数。

3 个答案:

答案 0 :(得分:2)

用此包裹您的函数调用:

(function($) {

  $(document).ready(function() {
    //Here you can manupilate the dom. Images are not loaded yet.
  });

  $(window).load(function() {
    //Here you can check for image widths.
  });

})(jQuery);

您可以使用以下方法检查客户端宽度:

$(window).width();

并且文档宽度为:

$(document).width();

答案 1 :(得分:1)

在加载图像后获取宽度:

$("#barely_slide article").on('load', 'img', function(){
    console.dir($(this).width());
});

答案 2 :(得分:0)

我认为您应该确保浏览器加载了您的图片,然后您可以尝试执行以下操作:

 $(document).ready(function(){ 
     var slide_width = 0;
     $("#barely_slide article").find("img").each(function(){
          console.dir($(this).width());
     });
     console.dir(slide_width);
 });