<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>练习</title>
<style type="text/css">
html,body{
margin: 0;
padding: 0;
}
.container{
margin: 20px;
}
#normal{
width: 200px;
height: 200px;
margin-right: 20px;
float: left;
position: relative;
}
#normal>img{
width: 200px;
height: 200px;
}
#mirror{
width: 100px;
height: 100px;
background: yellow;
opacity: 0.5;
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
#bigBox{
position: relative;
width: 200px;
height: 200px;
display: none;
overflow: hidden;
}
#bigBox>img{
width: 400px;
height: 400px;
position: absolute;
left: 0px;
top: 0;
}
</style>
</head>
<body>
<div class="container">
<div id="normal">
<img src="paul.png" />
<div id="mirror"></div>
</div>
<div id="bigBox">
<img src="paul.png" />
</div>
</div>
</body>
<script type="text/javascript">
var normal = document.getElementById('normal');
var norImg = normal.getElementsByTagName('img')[0];
var mirror = document.getElementById('mirror');
var bigBox = document.getElementById('bigBox');
var bigImg = bigBox.getElementsByTagName('img')[0];
// console.log(bigImg.offsetWidth);
var scale;
normal.onmouseenter = function(){
mirror.style.display = "block";
bigBox.style.display = 'block';
// console.log(bigImg.offsetWidth);
/*
遇到的坑:缩放比例一定要写在这里。因为一开始bigBox的display:none,故无法获取bigImg的属性。
*/
scale = bigImg.offsetWidth/norImg.offsetWidth;
// console.log(scale);
}
normal.onmousemove = function(event){
var e = event || window.event;
var x = e.clientX - mirror.offsetWidth/2 - normal.offsetLeft;
var y = e.clientY - mirror.offsetHeight/2 - normal.offsetTop;
if(x<0){
x=0
}
if(x>=normal.offsetWidth - mirror.offsetWidth){
x=normal.offsetWidth - mirror.offsetWidth
}
if(y<0){
y=0
}
if(y>=normal.offsetHeight - mirror.offsetHeight){
y=normal.offsetHeight - mirror.offsetHeight
}
mirror.style.left = x + 'px';
mirror.style.top = y + 'px';
bigImg.style.left = -mirror.offsetLeft*scale + 'px';
bigImg.style.top = -mirror.offsetTop*scale + 'px';
}
normal.onmouseleave = function(){
mirror.style.display = "none";
bigBox.style.display = 'none';
// console.log(bigImg.offsetWidth);
}
</script>
</html>