html部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="./css/index.css"/>
</head>
<body>
<div class="box" id="box">
<div class="small">
<img src="images/logo.png" width="350">
<div class="mask"></div>
</div>
<div class="big">
<img src="images/logo.png" width="800">
</div>
</div>
<script src="./index.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
css部分
*{
margin: 0;
padding: 0;
}
.box{
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big{
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.big img{
position: absolute;
}
.mask{
width: 175px;
height: 175px;
background: rgba(255,255,0,0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small{
position: relative;
}
js部分
// 获取页面中的滚动条的距离
function getScroll(){
return{
scrollTop:document.documentElement.scrollTop || document.body.scrollTop,
scrollLeft:document.documentElement.scrollLeft || document.body.scrollLeft
}
}
// 获取页面元素的x 和y 轴 的距离
function getPage(e){
return {
pageX:e.clientX + getScroll().scrollLeft,
pageY:e.clientY + getScroll().scrollTop,
}
}
// 鼠标移动到小盒子 显示遮盖的层 显示大图
var box = document.querySelector(".box")
// 小盒子
var smallBox = box.children[0]
// 大盒子
var bigBox = box.children[1]
// 遮盖层
var mask = smallBox.children[1]
// 大图片
var bigImg = bigBox.children[0]
smallBox.onmouseover = function(){
mask.style.display = "block";
bigBox.style.display = "block"
}
// 鼠标移除的是时候 消失
smallBox.onmouseout = function(){
mask.style.display = "none";
bigBox.style.display = "none"
}
// 鼠标在小盒子移动的时候 遮盖层跟着鼠标移动
smallBox.onmousemove = function(e){
e = e || event
// 获取鼠标在小盒子中的坐标
var x = getPage(e).pageX - box.offsetLeft;
var y = getPage(e).pageY - box.offsetTop;
// 让鼠标到mask的中点
x -= mask.offsetWidth / 2;
y -= mask.offsetHeight / 2;
// 控制范围
x = x < 0 ? 0 : x
y = y < 0 ? 0 : y
var maxY = smallBox.offsetHeight - mask.offsetHeight
var maxX = smallBox.offsetWidth - mask.offsetWidth
x = x > maxX ? maxX : x
y = y > maxY ? maxY : y
mask.style.left = x + 'px'
mask.style.top = y + 'px'
// 显示对于的大图部分
// 计算大图片的偏移
// mask移动的距离 / 大图片的距离 = mask最大能够移动的距离 / 大图片能够移动的距离
// 大图片移动的距离 = mask移动的距离 * 大图片最大能够移动的距离 / mask最大能够移动的距离
// 大图片能够移动的距离
var bigMaxX = bigImg.offsetWidth - bigBox.offsetWidth
var bigMaxY = bigImg.offsetHeight - bigBox.offsetHeight
var bigImgX = x * bigMaxX / maxX
var bigImgY = y * bigMaxY / maxY
bigImg.style.left = -bigImgX + 'px'
bigImg.style.top = -bigImgY + 'px'
}
图片随意替换