【问题标题】:How to get height of image manipulated with css如何使用css处理图像的高度
【发布时间】:2016-09-17 19:34:42
【问题描述】:

我有一些 div 框,里面有一张图片。我想要它做的是,如果图像高度小于其内部的 div 框高度,则向图像添加一个类。

但是我已经用css将图像设置为div框的100%宽度,所以当我在图像上使用jquery的.Height()时,它给了我原始大小。有什么建议吗?

<div class="boxe">
    <asp:Literal ID="imgProjekt1" runat="server" />
    <asp:Literal ID="litProjekt1" runat="server"/>
</div>

<div class="boxe forsideboxMiddle">
    <asp:Literal ID="imgProjekt2" runat="server" />
    <asp:Literal ID="litProjekt2" runat="server"/>
</div>

ID 为 imgProjekt1 和 ImgProjekt2 的文字从代码隐藏中生成一个普通的 img 标签。

【问题讨论】:

  • 你试过使用max-height和max-width吗?
  • 你试过$(img).outerHeight()吗?
  • max-height 和 max-with 在这种情况下不会有帮助
  • 使用 outerheight 将类放在所有 div 上,也包括图像大于 div 或相同大小的类

标签: javascript jquery html css image


【解决方案1】:

试试

var currentContentHeight = contentElement.offsetHeight;

【讨论】:

    【解决方案2】:

    您应该使用 clientWidth 和 clientHeight。

    var img = document.getElementById('imgProjekt1'); 
    var width = img.clientWidth;
    var height = img.clientHeight;
    

    编辑:

    $(window).load(function () { 
        var image = $('.boxe img');
        var box = $(".boxe");
        if (image[0].clientHeight > box[0].clientHeight) { 
            image.addClass('billedMiddle');
        }
    });
    

    【讨论】:

    • 我无法让它工作:$(window).load(function () { var image = $('.boxe img'); var width = image.clientWidth; var height = image. clientHeight; var box = $(".boxe"); if (height > box.clientHeight()) { image.addClass('billedMiddle'); } });
    • clientWidth 和 clientHeight 是 DOM 元素的属性。你可以这样做:var image = $('.boxe img')[0]; var box = $(".boxe")[0];
    • 那么脚本应该是什么样子呢?
    • 谢谢,该脚本使所有图像都获得该类,并且它应该只是高度小于框的图像,如果我转动 > arround 也不起作用
    【解决方案3】:

    使用 window.getComputedStyle 获取当前 DOM 的对象样式值。下面是如何提取 dom 对象的高度和宽度的代码示例。

    function Scale(width_offset, height_offset) {
       var imgs = document.getElementsByClassName("your img tag class name");
       for (var i = 0; i < imgs.length; i++) {
         var curr_width = parseInt(window.getComputedStyle(imgs[i]).width); // extract dom's width
         var curr_height = parseInt(window.getComputedStyle(imgs[i]).height); //extract dom's height
         imgs[i].style.width = curr_width + width_offset + "px";
         imgs[i].style.height = curr_height + height_offset + "px";
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 2016-10-16
      • 1970-01-01
      • 2017-07-25
      • 2016-02-07
      • 2016-11-01
      • 1970-01-01
      相关资源
      最近更新 更多