【问题标题】:CSS + jQuery: scale, center and rotate images inside containerCSS + jQuery:在容器内缩放、居中和旋转图像
【发布时间】:2019-11-01 10:21:49
【问题描述】:

如果你看看https://jsfiddle.net/0spv56uk/1/

我正在一个有容器的网站上创建一些东西。 这个容器不能再宽了(它可能会稍微高一些 - 以适应屏幕的大小)

在这个容器中,我将设置图像。它们的大小都不同。

这些图像/SVG 能够在单击按钮时旋转(如代码所示)。 我目前使用的是 90 度,但以后可能需要 45 度。

我遇到的问题是图像在旋转时溢出容器。 我需要它在旋转时在容器内缩放。 (容器的底部应该是可扩展的,但不是顶部)。 我在这里查看了其他线程,它们要么对比例进行硬编码(仅在您有单个图像时才有效),要么代码对我不太适用。

提前谢谢大家。

这一直让我做噩梦。

这是我的代码

var myArray = ['0deg', '90deg', '45deg','180deg','270deg']; var myIndex = 1; 
function nextRotation() { return 'rotate('+myArray[myIndex++%myArray.length];+')' };

$('#btn1').click(function(){
    $('#testImg').css('transform', nextRotation() );
    $('#testImg').css('-webkit-transform', nextRotation() );
    $('#testImg').css('-moz-transform', nextRotation() );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick=document.getElementById('testImg').src='https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/smile.svg'>Img1</button>
<button onclick=document.getElementById('testImg').src='https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/juanmontoya_lingerie.svg'>Img2</button>
<button onclick=document.getElementById('testImg').src='https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/php.svg'>Img3</button>
<button type="button" id="btn1" >Rotate Div</button>

<DIV id="container" style=" wid th:60%;border-style:dotted;">

  <DIV id="outer" width="100%">
    <img id ="testImg" src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/smile.svg"   style="width:100%;height:100%;">
  </DIV>
</DIV>

【问题讨论】:

    标签: javascript jquery html css css-transforms


    【解决方案1】:

    您可以通过将图像的高度与容器的宽度相匹配来使其工作。我还使容器的位置相对。

    请注意,您还使用了图像的透明度,这使它看起来像是留下了一堆空白空间。

    我刚刚添加了:

    $('#testImg').css('height', $('#container').width() );
    

    This looks to be working, but may stretch the image

    【讨论】:

    • 我想过这样的事情,但是。它似乎太有弹性了,并且不能在 45 度角下工作。我假设必须在边缘所在的位置进行某种数学计算并将其缩小。
    • 我一直在玩这样的东西,但是一旦我删除旋转jsfiddle.net/jhcn4f2w,它就无法缩放
    • 那么你在寻找什么旋转时,例如,45度?如果需要,图像边角应该被边框截断/隐藏,还是需要缩小图像以使所有边角仍然被包含和可见?
    • 它们应该像这个小提琴jsfiddle.net/jhcn4f2w 我唯一的问题是容器底部没有扩展。我想给底部一个最大尺寸和最小尺寸
    猜你喜欢
    • 2016-01-17
    • 2019-11-04
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多