使用图像高度调整div高度或使用相对URL调整图像高度

时间:2016-02-28 00:11:59

标签: html css responsive-design cq5

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

我的要求是我需要将图像设置为我的div的背景.SO div应该占据图像的高度,它应该保持不同断点的宽高比。所以我使用媒体查询在不同的图像显示不同的图像断点。下面是我的代码。为了实现这一点,我需要相对网址的图像高度。

<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>

如果我给图像提供过时的网址我正在变高。但是如果我给图像提供相对网址我无法获得高度

1 个答案:

答案 0 :(得分:0)

您可以在Javascript中执行此操作。使用数据属性可以获得一些很好的集成: 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"});
});
相关问题