我想在图像上获得缩放效果,但是在不增加屏幕尺寸的情况下,我能够对图像使用“ transform:scale()”来获得某种缩放,但是我不希望它占用的空间会增加,这就是我增加比例()时发生的情况。
我怎么能得到这个?我目前所取得的效果是在我的测试网站上,将来会是一个博客/投资组合:http://marcosroot.pythonanywhere.com/blog/
效果会随着图像中的悬停而发生。
PS:代码如下:
&__media {
transition: transform .25s ease-in-out;
&:hover {
transform: scale(1.025);
}
}
答案 0 :(得分:9)
这种方法没有依赖性,并且可以在所有现代浏览器中使用。 JavaScript
通过CSS
更新setProperty
变量,缩放图像的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>