【问题标题】:Sizing image to Fill Divs Based on Orientation根据方向调整图像大小以填充 div
【发布时间】:2016-09-20 20:28:25
【问题描述】:

基本上我想要做的是让图像填充一个 div,同时保持它们的纵横比。所以我使用 jquery 来识别它们是纵向还是横向,并从那里设置宽度或高度。

我的问题是代码提供了所有图像景观类。我不知道为什么……

谢谢!

HTML

    <div class="prop">
    <div class="propimage"><img src="{@image}" alt="{@prop_name}"></div>
    <div class="propname">{@prop_name}</div>
    <div class="propdescription">{@description}</div>
    <div class="propprice">{@price}</div>
    </div>

CSS

    .portrait img {
    width: 100%;
    }
   .landscape img {
    height: 100%;
    }
   .propimage img {
        display: block;
    }
    img {
        max-width: none;
    }
    .propimage {
        width: 100%;
        height: 300px;
        overflow: hidden;
        float: left;
    }

脚本

    <script>
    $(".propimage").each(function(){
        // Uncomment the following if you need to make this dynamic
        //var refH = $(this).height();
        //var refW = $(this).width();
        //var refRatio = refW/refH;

        // Hard coded value...
        var refRatio = 240/300;

        var imgH = $(this).children("img").height();
        var imgW = $(this).children("img").width();

        if ((imgW/imgH) < refRatio){ 
            $(".propimage").addClass("portrait");
        } else {
            $(this).addClass("landscape");
        }
    })
    </script>

【问题讨论】:

  • 什么决定什么时候应该是横向的,什么时候应该是纵向的?
  • 图片的原生尺寸(我认为!)

标签: javascript jquery html css


【解决方案1】:

请在 js fiddle 上上传您的代码或粘贴链接,以便我们查看您的代码的工作示例。同时试试这段代码

<script>
    $(".propimage").each(function(){
        // Uncomment the following if you need to make this dynamic
        //var refH = $(this).height();
        //var refW = $(this).width();
        //var refRatio = refW/refH;

        // Hard coded value...
        var refRatio = 240/300;

        var imgH = $(this).children("img").height();
        var imgW = $(this).children("img").width();

        if (imgW=<200 || imgH<=300)){ 
            $(this).children("img").css("width","100%");
            $(this).css("width","100%");
        } else {
             $(this).children("img").css("height","100%");
             $(this).css("height","100%");
        }
    })
    </script>

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多