问题描述
我想在图像上获得缩放效果但不增加屏幕尺寸,我可以使用“transform:scale()”为图像获得一种缩放,但我不想占用它的空间增加,这是我增加scale()时发生的事情。
我怎么能得到这个? 我已经实现的当前效果是在我的测试网站上,将来将是一个博客/产品组合: :
悬停在图像中会发生这种效果。
PS:代码如下:
&__media {
transition: transform .25s ease-in-out;
&:hover {
transform: scale(1.025);
}
}
1楼
这种方法没有依赖关系,适用于所有现代浏览器。
JavaScript
通过setProperty
更新CSS
变量,并在移动鼠标时动态更新缩放图像的background-position
。
const zoomify = (width, height) => { const el = document.querySelector('.zoomify'); el.style.width = `${width}px`; el.style.height = `${height}px`; el.addEventListener('mousemove', handleMouseMove, false); } function handleMouseMove(e) { const dimensions = this.getBoundingClientRect(); const [x, y] = [ e.clientX - dimensions.left, e.clientY - dimensions.top ]; const [percentX, percentY] = [ Math.round(100 / (dimensions.width / x)), Math.round(100 / (dimensions.height / y)) ]; this.style.setProperty('--mouse-x', percentX); this.style.setProperty('--mouse-y', percentY); } zoomify(320, 212);
* { box-sizing: border-box; } html, body { padding: 10px; } .starting-image { width: 100%; height: 100%; } .zoomify { display: inline-block; position: relative; overflow: hidden; } .zoomify::after { content: ''; position: absolute; z-index: 1; width: 100%; height: 100%; opacity: 0; background-image: url("https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w,%20https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w"); background-size: cover; background-position: center center; background-repeat: no-repeat; will-change: background-position; } .zoomify:hover .starting-image { opacity: 0; position: absolute; } .zoomify:hover::after { opacity: 1; background-size: 250%; cursor: zoom-in; background-position: calc(var(--mouse-x) * 1%) calc(var(--mouse-y) * 1%); }
<div class="zoomify"> <img class="starting-image" src="https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w,%20https://images.unsplash.com/photo-1528763216729-fb67cba479db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=728e3916b52b079634aa7c7f82af612d&auto=format&fit=crop&w=6774&q=80%206774w" alt="diner"> </div>