效果图:
实现起来相对简单,这里只做记录。
直接代码(内部数值未直接加减乘除,方便理解):
<!DOCTYPE html>
<html>
<head>
<title>放天猫放大镜效果</title>
<style type="text/css">
body {
padding: 100px 300px;
margin: 0;
}
img, #all, #all-right {
width: 300px;
height: 400px;
}
#all {
position: relative;
}
#cover {
display: none;
position: absolute;
top: 0;
left: 0;
width: 120px;
height: 150px;
background-image: url(./T12pdtXaldXXXXXXXX-2-2.png);
background-repeat: repeat;
}
#cover:hover {
cursor: move;
}
#all-right {
display: none;
position: absolute;
top: 99px;
left: 650px;
border: 1px solid gray;
background-image: url(./20190120215717_ffdei.jpg);
background-size: 750px 1066px;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div id="all">
<img src="./20190120215717_ffdei.jpg">
<span id="cover"></span>
</div>
<div id="all-right"></div>
<script type="text/javascript">
var all = document.getElementById('all');
var all_right = document.getElementById('all-right');
var cover = document.getElementById('cover');
all.addEventListener('mousemove', function(event) {
let { clientX, clientY } = event;
let [ coverX, coverY ] = [120 / 2, 150 / 2]; // 矩形框宽高的一半
if(clientX >= 300 && clientX <= (300 + coverX)) clientX = 300 + coverX;
if(clientX >= (300 + 300 - coverX) && clientX <= (300 + 300)) clientX = 300 + 300 - coverX;
if(clientY >= 100 && clientY <= (100 + coverY)) clientY = 100 + coverY;
if(clientY >= (100 + 400 - coverY) && clientY <= (100 + 400)) clientY = 100 + 400 - coverY;
let x = clientX - 300 - coverX;
let y = clientY - 100 - coverY;
cover.style.left = x + 'px';
cover.style.top = y + 'px';
all_right.style.backgroundPosition = `${-(x * (300 / 120))}px ${-(y * (400 / 150))}px`;
cover.style.display = 'block';
all_right.style.display = 'block';
})
all.addEventListener('mouseout', function(){
cover.style.display = 'none';
all_right.style.display = 'none';
})
</script>
</body>
</html>
所用图片: