【问题标题】:JQuery - How to get width or height of image which is automatically determined by proportion?JQuery - 如何获取由比例自动确定的图像的宽度或高度?
【发布时间】:2017-04-26 07:51:23
【问题描述】:

当我使用“img”标签时,如果我在css中只设置宽度而不设置高度值,图像的高度值将自动按比例计算。

但我发现我无法使用开发工具找到高度值,也无法使用 jQuery height() 方法获取该值。下面是一个例子:

HTML 代码

<img id="cat" src="./cat.png"/>

CSS 代码

img#cat {
    width:10em;
}

jQuery 代码

$(function() {
    alert($('img#cat').height());  // It returns 0 because there is no explicitly declared height value
});

有合适的 jQuery 方法吗?

【问题讨论】:

    标签: jquery css image height width


    【解决方案1】:

    您正在尝试在图像加载之前访问它。试试这个:

    $("#cat").load(function() {
      console.log("Image height: " + this.height)
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img id="cat" src="https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a_400x400.jpeg">

    【讨论】:

    • 谢谢!嗯..你能解释一下那个控制台对象吗?
    • @전세진 console.log 用于调试目的,它只是让您记录消息以检查您的程序是否正常工作。您可以在任何网络浏览器中查看控制台,这比使用警报更好。
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2014-09-10
    • 2012-01-28
    • 2011-12-24
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多