【问题标题】:image height using jquery in chrome problem在chrome问题中使用jquery的图像高度
【发布时间】:2010-12-17 03:56:36
【问题描述】:

$('img').height() 在 chrome 中返回 0,但在 IE 和 firefox 中返回实际高度。

在chrome中获取图像高度的实际方法是什么?

【问题讨论】:

  • 您是否在 img 标签本身或 CSS 中指定了 height
  • img是否可见,即是否已显示?
  • 不要在$(document).ready 上做事,而是在$(window).load 上做事。为我工作 — fortwaynewebdevelopment.com/…
  • 谢谢你,jibiel,为我工作!简单有效!
  • 根据您的情况,使用 $('#your_image').on('load', ...) 可能是合适的。

标签: jquery image google-chrome height


【解决方案1】:

刚刚做了一些实验,我发现

$(this).height();

返回 0 - 但是如果你只是使用普通的旧 JS

this.height;

我得到了正确的图像高度。

【讨论】:

    【解决方案2】:

    我使用的一个稍微难看但有效的解决方法是使用后端语言(在我的例子中是 php)来获取高度并将其设置在图像上,然后再将其发送到浏览器。

    它很丑,但简单快捷

    【讨论】:

      【解决方案3】:

      刚刚遇到同样的问题:通过 CSS 或 HTML 预先设置宽度和高度。

      【讨论】:

        【解决方案4】:

        预加载图像并设置回调函数可能是您想要的:

        // simple image preloader
        function getHeight(el,fn) {
            var img = new Image();
            img.onload = function() { fn(img.height); };
            img.src = el.attr("src");
        }
        
        $("img").each(function(){
            getHeight($(this),function(h){
                // what you need to do with the height value here
                alert(h);
            });
        });
        

        【讨论】:

          【解决方案5】:

          正如 Josh 提到的,如果图像还没有完全加载,jQuery 将不知道尺寸是多少。尝试这样的操作,以确保您仅在图像完全加载后才尝试访问其尺寸:

          var img = new Image();
          
          $(img).load( function() {
              //-- you can determine the height before adding to the DOM
              alert("height: " + img.height);
              //-- or you can add it first...
              $('body').append(img);
              //-- and then check
              alert($('body img').height());
          }).error( function() {
              //-- this will fire if the URL is invalid, or some other loading error occurs
              alert("DANGER!... DANGER!...");
          });
          
          $(img).attr('src', "http://sstatic.net/so/img/logo.png");
          

          【讨论】:

            【解决方案6】:

            尝试使用图像预加载器,here's one 我写信是为了回复another question

            【讨论】:

              【解决方案7】:

              我的假设是在图像完成加载之前调用此函数。您可以尝试延迟该功能以查看是否确实如此吗?如果是这种情况,您可以在运行函数之前使用计时器来作弊。

              检测图像何时加载有点复杂。 Have a look at this script for some ideas -- 也许对你有用。

              【讨论】:

              • 或者在正文 onload 事件中运行脚本,而不是在文档就绪事件中运行。它不那么精确,因为必须加载整个文档,但您可以确定图像已加载(假设它是代码中的图像,而不是某些 AJAX 加载的东西)。
              • @Frank,当 DOM 完成创建时会调用 body onload,但不能保证 DOM 中的资产已经完成加载(包括图像)。
              猜你喜欢
              • 1970-01-01
              • 2011-02-09
              • 1970-01-01
              • 2012-01-12
              • 1970-01-01
              • 2011-08-27
              • 2011-06-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多