<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style>
#leftWrap{
position: relative;
width: 300px;
height: 300px;
border: 1px solid black;
float: left;
}
#leftWrap img{
width: 300px;
height: 300px;
position: absolute;
}
#slider{
width: 150px;
height: 150px;
background: rgba(0,0,0,0.5);
position: absolute;
top: 0;
left: 0;
cursor: pointer;
display: none;
}
#rightWrap{
position: relative;
width: 300px;
height: 300px;
border: 1px solid black;
float: left;
left: 50px;
display: none;
overflow: hidden;
}
#img1{
width: 600px;
height: 600px;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="leftWrap">
<img src="img/2.jpg" alt="">
<div id="slider"></div>
</div>
<div id="rightWrap">
<img src="img/2.jpg" alt="" id="img1">
</div>
</body>
<script>
var leftWrap=document.getElementById('leftWrap');
var rightWrap=document.getElementById('rightWrap');
var img1=document.getElementById('img1');
var slider=document.getElementById('slider');
var maxImg=rightWrap.children[0];
// 鼠标放在左边时右边显示
leftWrap.onmousemove=function(event){
rightWrap.style.display="block";
slider.style.display='block';
// 获取鼠标左右移动
var event=event||window.event;
// 获取slider的宽度
// var sliderWidth=slider.offsetWidth;
// 当前鼠标的坐标点=可视区的距离-容器的偏移量
var disX=event.clientX-leftWrap.offsetLeft;
// 鼠标点在slider的中心
var x=disX-(slider.offsetWidth/2);
// 获取slider移动的最大宽度
var maxWidth=leftWrap.clientWidth-slider.offsetWidth;
if (x<=0) {
x=0;
}else if (x>=maxWidth) {
x=maxWidth;
}
slider.style.left=x+"px";
// 获取鼠标上下移动
// 获取slider的高度
// var sliderHeight=slider.offsetHeight;
// 获取鼠标的坐标点=可视的高度-容器距离上部的距离
var disY=event.clientY-leftWrap.offsetTop;
//让鼠标点在slider的中心
var y=disY-(slider.offsetHeight/2);
// 获取最大移动高度
var maxHeight=leftWrap.clientHeight-slider.offsetHeight;
if (y<=0) {
y=0;
}else if (y>=maxHeight) {
y=maxHeight;
}
slider.style.top=y+"px";
// 偏移的比例
var scaleX=x/maxWidth;
var scaleY=y/maxHeight;
img1.style.left=-(maxImg.offsetWidth-rightWrap.offsetWidth)*scaleX+"px";
img1.style.top=-(maxImg.offsetHeight-rightWrap.offsetHeight)*scaleY+"px";
}
// 鼠标离开时左边消失
leftWrap.onmouseout=function(){
rightWrap.style.display="none";
slider.style.display='none';
}
</script>
</html>
放大镜的难点:
1.onmousemove的使用
2.slider的宽高的比例
4.事件的获取