简体   繁体   English

如何在不影响图像尺寸的情况下对响应图像进行中心缩放?

[英]How to center-zoom with responsive images without affecting the image size?

I put together a jquery and css function to zoom in and out of an image on mouseover, while keeping the constraining box size constant. 我将jquery和css函数放在一起,以在鼠标悬停时放大和缩小图像,同时保持约束框的大小不变。 I found this as an example, and edited more to what I would like. 我以这个为例,并对其进行了更多编辑。

Demo is here: https://jsfiddle.net/2fken8Lg/1/ 演示在这里: https : //jsfiddle.net/2fken8Lg/1/

Here is the code: 这是代码:

JS: JS:

 $('.zoom img').on({
   mouseover: function() {
     var $scale = 1.5;
     if (!$(this).data('w')) {
       var $w = $(this).width();
       var $h = $(this).height();
       $(this).data('w', $w).data('h', $h);
     }
     $(this).stop(true).animate({
       width: $(this).data('w') * $scale,
       height: $(this).data('h') * $scale,
       left: -$(this).data('w') * ($scale - 1) / 2,
       top: -$(this).data('h') * ($scale - 1) / 2
     }, 'fast');
   },
   mouseout: function() {
     $(this).stop(true).animate({
       width: $(this).data('w'),
       height: $(this).data('h'),
       left: 0,
       top: 0
     }, 'fast');
   }
 });

CSS: CSS:

.zoom {
  position: relative;
  float: left;
  margin: 30px 0 0 30px;
  width: 400px;
  height: 180px;
  overflow: hidden;
  border: 1px solid #000;
}

img {
  position: absolute;
  width: 400px;
  height: 180px;
}

HTML: HTML:

<div class="zoom">
  <img src="https://www.lamborghini.com/en-en/sites/en-en/files/DAM/it/models_gateway/blocks/special.png">
</div>

It works great with a fixed image size, but my question is how do I expand it to responsive images? 它在固定图像大小的情况下效果很好,但是我的问题是如何将其扩展到响应图像? My webpage is based purely on responsiveness so I can't have a fixed css width or height anywhere because it would mess up different browser sizes. 我的网页纯粹基于响应能力,因此我无法在任何地方设置固定的CSS宽度或高度,因为它会弄乱不同的浏览器大小。 Is there anyway to do what I am trying to accomplish for responsive images, or without css? 无论如何,有没有要做我要为响应图像完成的工作,或者没有CSS?

The correct way to do this is to use transforms within css, this answer was due to a suggestion by the user @Keith. 正确的方法是在CSS中使用转换,此答案归因于用户@Keith的建议。 The example JS fiddle below will describe how to accomplish a zoomed-center look without affecting responsiveness. 下面的示例JS小提琴将描述如何在不影响响应性的情况下实现缩放中心外观。

Demo: https://jsfiddle.net/2fken8Lg/2/ 演示: https : //jsfiddle.net/2fken8Lg/2/

HTML: HTML:

<div class="zoom">
  <img src="https://www.lamborghini.com/en-en/sites/en-en/files/DAM/it/models_gateway/blocks/special.png">
</div>

CSS: CSS:

.zoom {
  position: relative;
  border: 1px solid #333;
  overflow: hidden;
  width: 100%;
}
.zoom img {
  max-width: 100%;

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.zoom:hover img {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM