父内部div在内部图像旋转时更改尺寸

时间:2015-08-12 10:19:13

标签: javascript jquery html css rotation

我有一个包含一个或多个图像的模态,这些图像可以旋转。

我的问题是当图像旋转它溢出父div。我希望容器能够改变尺寸以始终适合图像(图像)。

我创建了一个 codepen 来查看。

我试图改变很多很多 css 属性而没有成功......

玉:

.overlay
.fake-modal
  .content
    img.img(src='http://lorempixel.com/output/abstract-q-c-300-200-2.jpg')
    .wrapper
      button.left rotate left
      button.right rotate right

减:

.overlay {
  background-color: rgba(0, 0, 0, .7);
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.fake-modal {
  background-color: #fff;
  padding: 10px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: auto;
  height: auto;
  z-index: 1;

  .content {
    position: relative;

    .wrapper {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
}

JS:

var angle = 0;
var btnLeft = $('.left');
var btnRight = $('.right');

btnLeft.on('click', function (e) {
  e.preventDefault();
  angle = angle - 90;
  rotate(angle);
});

btnRight.on('click', function (e) {
  e.preventDefault();
  angle = angle + 90;
  rotate(angle);
});

function rotate(rotateDegrees) {
  var r = 'rotate(' + rotateDegrees + 'deg)';
  var img = $('.img');
  img.css({
    '-moz-transform': r,
    '-webkit-transform': r,
    '-o-transform': r,
    '-ms-transform': r
  });
}

2 个答案:

答案 0 :(得分:1)

使用getBoundingClientRect()

解决

Codepen:http://codepen.io/anon/pen/BNENge

答案 1 :(得分:0)

您可以将固定宽度和高度设置为div contaning图像。 http://codepen.io/anon/pen/XbQXJP

`.overlay {
  background-color: rgba(0, 0, 0, .7);
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.fake-modal {
  background-color: #fff;
  padding: 10px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: auto;
  height: auto;
  z-index: 1;

  .content {
    position: relative;

    .imgContainer {
      position: relative;
      width: 300px;
      height: 200px;

      .img {
        position: absolute;
        margin-left: -150px;
        margin-top: -100px;
        top: 50%;
        left: 50%;
      }
    }

    .wrapper {
      position: absolute;
      top: 10px;
      right: 10px;
    }
  }
}`