<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.f1 {
width: 400px;
height: 600px;
}
.b3 {
position: relative;
height: 398px;
border: 1px solid #ccc;
}
/* .b3 img {
height: 100%;
width: 100%;
} */
.zhe {
display: none;
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 300px;
background-color: #fede4f;
/* opacity透明 */
opacity: .5;
border: 1px solid #ccc;
/* 鼠标经过变成十字箭头 */
cursor: move;
}
.big {
display: none;
position: absolute;
left: 410px;
top: 0;
width: 500px;
height: 500px;
border: 1px solid #ccc;
overflow: hidden;
z-index: 999;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
.xiao {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div class="f1">
<div class="b3">
<img src="images/b3.png" alt="" class="xiao">
<div class="zhe"></div>
<div class="big">
<img src="images/big.jpg" alt="" class="bigImg">
</div>
</div>
</div>
<script>
var b3 = document.querySelector('.b3');
var zhe = document.querySelector('.zhe');
var big = document.querySelector('.big');
b3.addEventListener('mouseover', function() {
zhe.style.display = 'block';
big.style.display = 'block';
})
b3.addEventListener('mouseout', function() {
zhe.style.display = 'none';
big.style.display = 'none';
})
//2.鼠标移动的时候,让黄色的盒子跟着鼠标来走
b3.addEventListener('mousemove', function(e) {
//(1).线计算出鼠标在盒子内的坐标
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
//(2).减去盒子高度300的一半 是150 就是我们zhe 的最终 和top值
//(3).zhe移动的距离
var zheX = x - zhe.offsetWidth / 2
var zheY = y - zhe.offsetHeight / 2
//(4).如果x坐标小于0 就让它停在0的位置
var xx = b3.offsetWidth - zhe.offsetWidth;
var yy = b3.offsetHeight - zhe.offsetHeight;
if (zheX <= 0) {
zheX = 0;
} else if (zheX >= xx) {
zheX = xx;
}
if (zheY <= 0) {
zheY = 0;
} else if (zheY >= yy) {
zheY = yy;
}
zhe.style.left = zheX + 'px';
zhe.style.top = zheY + 'px';
//3.大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离
//大图
var bigImg = document.querySelector('.bigImg');
//大图片的最大距离
var bigMax = bigImg.offsetWidth - big.offsetWidth;
//大图片的移动距离
var bigX = zheX * bigMax / xx;
var bigY = zheY * bigMax / yy;
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
})
</script>
</body>
</html>