【问题标题】:dynamically crop image css javascript/jquery动态裁剪图像 css javascript/jquery
【发布时间】:2018-05-24 02:28:41
【问题描述】:

我正在寻找一种在固定高度 div 内动态垂直居中图像的方法。我无法将图像设为背景图像。我将拥有从 300x375 到 300x240 的各种高度图像。我内部 div 的高度将是 240,如果图像高于 240,我想将图像居中。因此,高度为 375 的它会裁剪顶部和底部 76.5 像素。如果它是 300 的高度,它会在顶部和底部裁剪 30px。

我已经尝试了多种方法,但是当我将较大的图像进行裁剪时,似乎较小的图像会变得一团糟。

我将尝试制作一个 jsfiddle,但希望将其发布,因为我猜这相当简单,即使我无法找到解决方案。

【问题讨论】:

    标签: javascript jquery css image


    【解决方案1】:

    不一定要用js,用flexbox试试。

    HTML

    <div id="root">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1024px-Circle_-_black_simple.svg.png">
    </div>
    

    CSS

    #root {
      width: 300px;
      height: 240px;
      overflow: hidden;
    
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    
    #root > img {
      width: 300px;
      height: 375px;
    }
    

    https://codepen.io/jc3m-the-flexboxer/pen/deEvpM

    【讨论】:

    • 比我的答案更好。
    【解决方案2】:

    假设这是一个 HTML 布局

    <div class="one">
      <img src="https://placeimg.com/300/375/any">
    </div>
    <div class="one">
      <img src="https://placeimg.com/300/240/any">
    </div>
    

    您可以遍历 div 并将图像的顶部边距设置为负值,即 240 与图像高度之间的差值的一半

    $(document).ready(function() {
        $('.one img').each( function() {
        if( $(this).height() > 240 ) {
            var diff = ($(this).height() - 240) /2
          $(this).css('margin-top', (diff * -1) + 'px')
        }
      })
    })
    

    需要将 div 设置为溢出隐藏才能正常工作。

    小提琴:https://jsfiddle.net/calder12/29s5gnLq/

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 2012-11-18
      • 2022-01-23
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多