【问题标题】:How to get the height of an image in javascript如何在javascript中获取图像的高度
【发布时间】:2013-11-27 23:24:18
【问题描述】:

假设图像的原始高度为 200 像素或低于 100 像素。然后我设置图像的“最大高度:100px”。我将如何获得它的显示高度。我试过 $('img').height()。但它只是返回一个 0 值吗?

【问题讨论】:

  • 请贴出你的htmn代码和js代码。提前致谢。
  • 你为什么不尝试获得最大高度呢? $('#yourImage').css('max-height');
  • 如果图像的高度低于它的最大高度怎么办?我不想返回最大高度本身。

标签: javascript jquery height max


【解决方案1】:

使用window.getComputedStyle(Firefox、Opera、Safari):

示例:

<img style="height:100px;max-height:100px;" src="img.gif" id="test">
var img = document.getElementById('test');
var height = window.getComputedStyle(img).height;
console.log(height)

将输出 100px

对于 IE 你可以使用

var height = img.currentStyle.height;

【讨论】:

    【解决方案2】:

    使用简单的 JavaScript:

    var img = document.getElementById('imageid'); // use the id of your image
    var height = img.clientHeight;
    

    【讨论】:

      【解决方案3】:

      您需要 $('img').innerHeight() - 获取匹配元素集中第一个元素的当前计算高度,包括填充但不包括边框。 http://api.jquery.com/innerHeight/

      【讨论】:

        【解决方案4】:
        $(document).ready(function() {
        $("img").load(function() {
            alert($(this).height()); // for height
            alert($(this).width());  // for width
        });
        });
        

        【讨论】:

          【解决方案5】:

          确保您已在此脚本上方初始化 jQuery,因为在这种情况下,您似乎正在尝试通过“$”命令使用 jQuery。

          <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
          

          将上面的代码放在文档的头部。

          在身体,但在形象

          <body>
              <img src="img.jpg" id="new-image" />
          </body>
          

          上面是HTML,图片的ID是“new-image”

          可以使用 jQuery 通过在 ID 前添加 # 来选择 ID

          例如“#new-image”

          $(document).ready(function(){
          
              // Retrieves computed image height and stores to variable "imgHeight"
              var imgHeight = $('#new-image').height();
          
              // Shows current computed/displayed height in development console
              console.log(imgHeight);
          
              // If you don't know how to access the development console
              // You can also use alert (but you should learn to use the console!)
              alert(imgHeight);
          }
          

          确保将以上代码包装在脚本标签中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-06-19
            • 2018-01-04
            • 2013-01-03
            • 2021-08-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-06
            相关资源
            最近更新 更多