CSS转换比例切断图像

时间:2018-07-27 14:07:57

标签: css

我在容器中有一个具有溢出滚动的图像,我将实现缩放功能,因此对于缩放,我想按比例放大图像。在下面提供的代码段中,有两张图片,第一张图片的比例值为1,您可以通过垂直和水平滚动查看整个图片。但是,当其比例值为2时,我无法通过沿x或y方向滚动来查看整个图像。看起来像放大图像会使图像被剪切掉。解决该问题的解决方案是什么?

div {
  height: 200px;
  width: 500px;
  overflow: scroll;
}

img {
  transform: scale(1)
}

.div2 {
margin-top: 5px;
}

.div2 img {
 transform: scale(2)
}
<div>
  <img src="https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg" />
</div>

<div class="div2">
  <img src="https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg" />
</div>

2 个答案:

答案 0 :(得分:0)

Transform: scale(2)无法为.div2定义img的width / height值

但是您可以使用jquery进行缩放。

示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <style>
    div {
      height: 200px;
      width: 500px;
      overflow: scroll;
    }

    img {
      transform: scale(1)
    }

    .div2 {
      margin-top: 5px;
    }
    </style>
</head>

<body>
	
    <div>
        <img src="https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg" />
    </div>

    <div class="div2">
        <img src="https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg" />
    </div>

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
		  var originImgWidth = $('.div2 > img').width();
		  var originImgHeight = $('.div2 > img').height();
		  var ratio = 2;

		  //Check img orgin size
		  //console.log('originSize:', originImgWidth, originImgHeight);

		  $('.div2 > img').css({
		      'width': originImgWidth * ratio + 'px',
		      'height': originImgHeight * ratio + 'px'
		  })
    </script>
</body>

</html>

答案 1 :(得分:0)

不确定您要做什么,但这也许会有所帮助。这是使用比例和过渡的两个示例。 transform-origin将更改图片的缩放方式。

div {
  height: 200px;
  width: 500px;
  overflow: scroll;
}

img {
  width: 100%;
  height: 100%;
  background-image: url(https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg);
  background-size: cover;
  transform-origin: right;
  transform: scale(1);
  transition: transform 1s ease;
}

img:hover {
  transform: scale(2);
}
    
.div2 img {
  background-image: url(https://www.tennisworldusa.org/imgb/57551/roger-federer-to-take-a-threemonth-break-i-won-t-play-roland-garros-.jpg);
  background-size: cover;
  transform-origin: center;
  transform: scale(1);
  transition: transform 1s ease;
}

.div2 img:hover {
  transform: scale(2);
}
    
<div>
  <img>
</div>
<div class="div2">
  <img>
</div>