测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#small-box,#big-box{
width: 400px;
height: 400px;
float: left;
overflow: hidden;
}
#small-box{
position: relative;
}
#drag{
width: 200px;
height: 200px;
position: absolute;
top:0;
left:0;
background:rgba(255,255,255,0.5);
display: none;
}
#big-box{
display: none;
position: relative;
}
#big-img{
position: absolute;
left:0;
top:0;
}
</style>
</head>
<body>
<div id="container">
<div id="small-box">
<img src="images/1.jpg">
<span id="drag"></span>
</div>
<div id="big-box">
<img id="big-img" src="images/2.jpg">
</div>
</div>
<script>
// <!-- offset用来取值
// syle 用来设置 -->
var oSmallbox = document.getElementById("small-box");
var oBigbox = document.getElementById("big-box");
var oDrag = document.getElementById("drag");
var oBigImg = document.getElementById('big-img');
oSmallbox.onmouseover = function(){
oDrag.style.display= "block";
oBigbox.style.display = "block";
}
oSmallbox.onmouseout = function(){
oDrag.style.display = "none";
oBigbox.style.display = "none";
}
oSmallbox.onmousemove = function(e){
oDrag.style.left = e.clientX - oDrag.offsetWidth/2 + "px";
oDrag.style.top = e.clientY - oDrag.offsetHeight/2 + "px";
if(oDrag.offsetLeft <=0){
oDrag.style.left = 0;
}
var maxleft = oSmallbox.offsetWidth-oDrag.offsetWidth
if(oDrag.offsetLeft>maxleft){
oDrag.style.left = maxleft +"px";
}
if(oDrag.offsetTop<=0){
oDrag.style.top=0;
}
var maxheight = oSmallbox.offsetHeight-oDrag.offsetHeight
if(oDrag.offsetTop >= maxheight){
oDrag.style.top = maxheight + "px";
}
var smallDis = oSmallbox.offsetWidth - oDrag.offsetWidth;
var bigDis = oBigImg.offsetWidth - oBigbox.offsetWidth;
var smallDisY = oSmallbox.offsetHeight - oDrag.offsetHeight;
var bigDisY = oBigImg.offsetHeight - oBigbox.offsetHeight;
var xPro = oDrag.offsetLeft/smallDis;
oBigImg.style.left = -bigDis*xPro + "px";
oBigImg.style.top = -oDrag.offsetTop/smallDisY*bigDisY + "px";
}
</script>
</body>
</html>
测试结果