<style>
*{
margin:0;
padding:0;
}
body{
width: 960px;
margin: 40px auto;
}
/*必须有定位,move才能根据他进行定位,后面才能固定滑块的位置*/
#small{
width: 350px;
height: 450px;
border:1px solid green;
position: absolute;
overflow: hidden;
}
/*设置图片宽度为整个div宽度*/
#small img{
width: 100%;
height: 100%;
}
/*设置左浮动*/
div{
float:left;
}
/*move块要设置绝对定位,这样才能不占用文档流,不被遮挡*/
#move{
width: 100px;
height: 100px;
position: absolute;
top:0px;
left:0px;
background-color: black;
display: none;
opacity:0.4;
}
#look_girl{
position: absolute;
left:0px;
top:0px;
}
/*讲解的时候要去掉overflow,演示全图*/
#big{
border:1px solid red;
width: 340px;
height:340px;
overflow: hidden;
display: none;
position: absolute;
}
</style>
<body>
<div id="small">
<img src="./images1/2.jpg" />
<p id="move"></p>
</div>
<div id="big">
<img src="./images1/2.jpg" id="look_girl" />
</div>
</body>
<script>
//1获取节点
var small = document.getElementById('small');
var move = document.getElementById('move');
var big = document.getElementById('big');
var look_girl = document.getElementById('look_girl');
small.onmousemove = function(e){
//绑定事件
var e = event ||window.event
// console.log(1)
//获取鼠标的位置
var moveX = e.clientX;
var moveY = e.clientY;
// console.log(moveX,moveY)
//获取鼠标在透明框中间点的的位置
var moveLeft = moveX-small.offsetLeft-move.offsetWidth/2;
var moveTop = moveY-small.offsetTop-move.offsetHeight/2;
// console.log(moveLeft,moveTop)
//判断透明框是否小于左边的边界最小距离
if(moveLeft<0) moveLeft=0;
if(moveTop<0) moveTop=0;
//声明一个变量接收可以移动的距离,
var enLeft = small.offsetWidth-move.offsetWidth;
var enTop = small.offsetHeight-move.offsetHeight;
//判断透明框最大的移动距离,如果超过就让它等于最大距离
if(moveLeft>enLeft) moveLeft=enLeft;
if(moveTop>enTop) moveTop=enTop;
//让放大的图片在左边显示
big.style.left = small.offsetLeft+small.offsetWidth+'px';
big.style.top = small.offsetTop+'px'
//定义大图的位置
var big_X = moveLeft/(small.offsetWidth-move.offsetWidth)*(big.offsetWidth-look_girl.offsetWidth);
var big_Y = moveTop/(small.offsetHeight-move.offsetHeight)*(big.offsetHeight-look_girl.offsetHeight);
//把大图的位置赋值
look_girl.style.left=big_X+'px'
look_girl.style.top=big_Y+'px'
move.style.left = moveLeft+'px';
move.style.top = moveTop+'px'
move.style.display = 'block'
big.style.display = 'block'
}
</script>