结构 要仔细设计
鼠标在small盒子内移动
big图片跟随着移动
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.small{
width: 350px;
height: 350px;
position: relative;
overflow: hidden;
}
.mask{
width: 100px;
height: 100px;
background:rgba(255,255,0,0.4);
position: absolute;
left: 0;
top: 0;
cursor: move;
display: none;
}
.big{
width: 450px;
height: 450px;
border: 1px solid #ccc;
position: absolute;
top: 0;
left: 360px;
overflow: hidden;
display: none;
}
.big img{
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="fdj">
<div class="small">
<img src="images/01.jpg" alt=""/>
<div class="mask"></div>
</div>
<div class="big">
<img src="images/001.jpg" alt=""/>
</div>
</div>
</body>
</html>
<script>
var fdj = document.getElementById("fdj");
var small = fdj.children[0];
var mask = small.children[1];
var big = fdj.children[1];
small.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
}
small.onmouseout = function () {
mask.style.display = "none";
big.style.display = "none";
}
//鼠标在small盒子内移动
var x = 0,y=0;
small.onmousemove= function (event) {
var event = event || window.event;
x = event.clientX - this.offsetParent.offsetLeft - mask.offsetWidth/2;
//this.offsetParent.offsetLeft是box盒子的左侧距离,因为small,box都有定位,所以this.offsetLeft一直是0;要用box的left值才行.
y = event.clientY - this.offsetParent.offsetTop -mask.offsetHeight/2;
if(x<0){
x=0;
}else if(x>small.offsetWidth-mask.offsetWidth){
x = small.offsetWidth-mask.offsetWidth;
}
if(y<0){
y=0;
}else if(y>small.offsetHeight-mask.offsetHeight){
y = small.offsetHeight-mask.offsetHeight;
}
mask.style.left = x +"px";
mask.style.top= y+ "px";
//big图片跟着变化
var bigImg = big.children[0];
bigImg.style.left = -x*(big.offsetWidth/small.offsetWidth) +"px";
bigImg.style.top= -y*(big.offsetHeight/small.offsetHeight) + "px";
}
</script>