首页 文章

无法在chrome中获得对象的真实高度/宽度

提问于
浏览
9

我有一个问题,如果我在css中设置图像高度并尝试获得高度/宽度,我会在不同的浏览器中得到不同的结果 . 有没有办法在所有浏览器中获得相同的维度?

你可以在这里找到一个实例<-Removed

这个概念是这样的:

CSS:
img{
  height:100px;
  }

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

输出Firefox:img height:100 img width:150

输出Chrome:img高度:100 img宽度:0

输出Chrome:img高度:100 img宽度:93?

我从StackOverflow尝试过这个:stackoverflow.com/questions/1873419/jquery-get-height-width

但仍然得到相同的结果

谁知道一个好的解决方案?

4 回答

  • 0

    图像未加载到 document.ready 中,您需要使用 window.load 事件来确保它们存在,如下所示:

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

    Here's a quick read on the difference,重要的是图片被加载 .

  • 24

    Nick Craver使用$(window).load()的答案是正确的,但图像也有一个load()方法,它允许更精细的粒度,特别是如果可能要加载多个图像 .

    $(document).ready(function(){ 
        $("#top_img_0").load (function (){
          $("#text").append( "height: " + $("#top_img_0").attr("height")+"
    " ); $("#text").append( "width: " + $("#top_img_0").attr("width")+"
    " ); }); });
  • 6

    它看起来像是一种竞争条件,至少对我来说是使用Chrome . 在获得尺寸时,图像未完成加载 . 我将所有内容设置为在200ms超时后触发,并显示实际宽度/高度 .

    $(document).ready(function() {
            setTimeout("getImageDimensions()", 200);
        });
    
        function getImageDimensions() {
            var pic_real_width;
            var pic_real_height;
    
            $("#topContent img").each(function() {
                var $this = $(this);
                $this.removeAttr("width");
                $this.removeAttr("height");
                $this.css({ width: 'auto', height: 'auto' });
    
                pic_real_width = $this.width();
                pic_real_height = $this.height();
                $this.css({ width: '', height: '100px' });
            });
    
            $("#text").append(" height: " + pic_real_height/*$("#top_img_0").attr("height")*/ + "
    "); $("#text").append(" width: " + pic_real_width/*$("#top_img_0").attr("width")*/ + "
    "); }

    经过测试,适用于Chrome,IE和Firefox . 全部显示2008 x 3008 .

  • 1

    更换

    $this.css({width: '', height: ''});
    

    $this.css({width: 'auto', height: 'auto'});
    

    Opera 10.10高度/宽度2008 x 3008

相关问题