效果图:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.big {
position: relative;
margin-left: 50px;
margin-top: 50px;
width: 300px;
height: 300px;
border: 1px solid #ccc;
background: url(s3.png) no-repeat center center;
}
.small {
display: none;
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 200px;
background-color: peru;
opacity: .3;
}
.img {
/* display: none; */
position: absolute;
left: 350px;
top: 0;
width: 500px;
height: 500px;
border: 1px solid #ccc;
overflow: hidden;
}
img {
position: absolute;
left: 0;
right: 0;
}
</style>
<script>
window.addEventListener('load', function () {
var big = document.querySelector('.big');
var small = document.querySelector('.small');
var img = document.querySelector('img');
big.addEventListener('mouseover', function () {
small.style.display = 'block';
img.style.display = 'block';
})
big.addEventListener('mouseout', function () {
small.style.display = 'none';
img.style.display = 'none'
})
document.addEventListener('mousemove', function (e) {
var x = e.pageX - big.offsetLeft; //鼠标到左框的距离
var y = e.pageY - big.offsetTop; //鼠标到上框的距离
var smallx = x - small.offsetWidth / 2 //内盒到外盒左边框的距离
var smally = y - small.offsetHeight / 2 //内盒到外盒上边框的距离
var maxx = big.offsetWidth - small.offsetWidth; //最多移动距离x
var maxy = big.offsetHeight - small.offsetHeight; //最多移动距离y
if (smallx <= 0) {
smallx = 0 //如果内盒到左边的移动距离小于0,就让这个距离等于0
} else if (smallx >= maxx) {
smallx = maxx //如果距离大于最大距离,就让这个距离等于最大移动距离
}
if (smally <= 0) {
smally = 0
} else if (smally >= maxy) {
smally = maxy;
}
small.style.left = smallx + 'px'; //把距离赋给small
small.style.top = smally + 'px';
//-------------------------------以下是放大的图片的位移代码
var imgx = smallx * img.offsetWidth / small.offsetWidth;
var imgy = smally * img.offsetHeight / small.offsetHeight;
img.style.left = -imgx + 'px';
img.style.top = -imgy + 'px';
})
})
</script>
</head>
<body>
<div class="big">
<div class="small"></div>
</div class="big">
<div class="img">
<img src="big.jpg" alt="">
</div>
</body>
</html>
以下是图片素材: