jquery的height()方法在一些瀏覽器工作不正常的解決方法

CSS:
img{
  height:100px;
  }

Script:
$(document).ready(function(){
    $("#text").append($("#img_0").attr("height"));
    $("#text").append($("#img_0").attr("width"));
});

Output Firefox: img height: 100 img width: 150

Output Chrome: img height: 100 img width: 0

Output Chrome: img height: 100 img width: 93?

solution:

The images aren't loaded in document.ready, you need to use the window.load event to make sure they're present, like this:

$(window).load(function(){
    $("#text").append($("#img_0").height());
    $("#text").append($("#img_0").width());
});

The first answer to use $(window).load() is correct, but the images also have a load() method, which allows finer granularity, especially if there are perhaps multiple images to load.

  $(document).ready(function(){ 
    $("#top_img_0").load (function (){
      $("#text").append( "height: " + $("#top_img_0").attr("height")+"<br/>" );
      $("#text").append( "width: " + $("#top_img_0").attr("width")+"<br/>" );   
      }); 
  });

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章