【问题标题】:Adjust div height with image height or how to get height of image with relative URL使用图像高度调整 div 高度或如何使用相对 URL 获取图像高度
【发布时间】:2016-02-28 11:45:28
【问题描述】:

我能够使用过时的 URL 检索图像高度。但我的要求是获取从 DAM(CMS) 获取的图像高度,例如我需要获取本地大坝中存在的图像高度。

我的要求是我需要将图像设置为我的 div 的背景。所以 div 应该采用图像的高度,并且它应该在不同的断点保持纵横比。所以我使用媒体查询以不同的方式显示不同的图像断点。下面是我的代码。为了实现这一点,我需要图像的高度,即相对 url。

<div class="box container-fluid" id="bgImageBox" >
     <cq:include path="box-content" resourceType="foundation/components/parsys"/>
</div>
<% 
    java.awt.image.BufferedImage bimg = javax.imageio.ImageIO.read(new java.net.URL("content/dam/marquee/hp-mq-samsung-galaxy-s7-edge-presale-dsktp.jpg"));
     int width_i   = bimg.getWidth();
     int height_i  = bimg.getHeight();
    %>


<style>
#bgImageBox {

    border-color: red;
    background-repeat: no-repeat;
    background-size: 100%;
height:<%=height_i%>px;
    }

    @media screen and (min-width: 1px) and (max-width: 723px){
#bgImageBox {
    background-image: url(<%=mobileURL%>);
}
    }


@media  screen and (min-width: 1240px){
 #bgImageBox { background-image: url(<%=desktopUrl%>); }
    }
@media only screen and  (min-width: 940px) and (max-width: 1239px) {

     #bgImageBox { background-image: url(<%=desktopUrl%>); }
}

@media only screen and (min-width: 724px) and (max-width: 939px) {

     #bgImageBox { background-image: url(<%=tabletUrl%>); }
}
</style>

如果我给图像提供过时的 url,我会得到高度。但是如果我给图像提供相对 url,我就无法得到高度

【问题讨论】:

  • 您应该添加有关您迄今为止尝试过的其他信息。
  • 我更新了问题请通过

标签: html css responsive-design aem


【解决方案1】:

您可以改用 Javascript 来执行此操作。使用 data-attributes 你会得到一些很好的集成: HTML:

<div class="box container-fluid" data-url="insert_url_here">
    <!-- ... -->
</div>

Javascript(使用 jQuery):

$("[data-url]").each(function() {
    var url = $(this).data("url"), img = new Image(), width, height, ratio;

    img.src = url;

    width = img.width;
    height = img.height;
    ratio = width / height;

    var newHeight = $(this).width() / ratio;
    $(this).css({
        "background": "url(" + url + ") no-repeat",
        "background-size": "cover"
        "height": newHeight + "px"});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    相关资源
    最近更新 更多