参考:震撼!CSS3+JS放大镜模式竟然能完美实现
参考文章中介绍了原理,我这里稍微改变了一下
<html>
<body>
<div class="bruce">
<div class="magnifier">div>
div>
body>
<script>
let magnifier=document.querySelector(".magnifier");
let isshow = false;
magnifier.addEventListener("click",e=>{
const fz = window.getComputedStyle(magnifier, '::before').getPropertyValue('--sizew');
if(isshow){
e.target.style.setProperty("--x",`0`);
e.target.style.setProperty("--y",`0`);
}else{
e.target.style.setProperty("--x",`${e.offsetX}px`);
e.target.style.setProperty("--y",`${e.offsetY}px`);
}
isshow = !isshow;
});
script>
<style>
:root{
--ratio: 1.5;
--box-w: 100vw;
--box-h: 80vh;
--outbox-w: calc(var(--box-w) * var(--ratio));
--outbox-h: calc(var(--box-h) * var(--ratio));
}
/* .bruce{
margin-top: 50px;
} */
.magnifier{
--x:0;
--y:0;
overflow: hidden;
position: relative;
width: var(--box-w);
height: var(--box-h);
background: url("a.jfif") no-repeat center/100% 100%;
/* cursor: grabbing; */
}
.magnifier::before{
--sizew: 0;
--sizeh: 0;
--scale-x: calc(var(--sizew) / var(--ratio) - var(--ratio) * var(--x));
--scale-y: calc(var(--sizeh) / var(--ratio) - var(--ratio) * var(--y));
position: absolute;
left: var(--x);
top: var(--y);
/* border-radius: 100%; */
border-radius: 5%;
width: var(--sizew);
height: var(--sizeh);
background: #333 url("a.jfif") no-repeat var(--scale-x) var(--scale-y)/var(--outbox-w) var(--outbox-h);
/* box-shadow: 1px 1px 3px rgba(0,0,0,.5); */
content: "";
will-change: left,top;
transform: translate(-60%,-70%);
}
.magnifier:hover::before{
--sizew: 500px;
--sizeh: 650px;
}
style>
html>