<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>放大镜</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.box{
350px;
height: 350px;
margin: 100px;
border: 1px solid #aaa;
position: relative;
}
.box .thumb{
450px;
height: 450px;
border: 1px solid #aaa;
overflow: hidden;
position: absolute;
left: 355px;
top: 0;
display: none;
}
.box .normal .zoom{
200px;
height: 200px;
background-color:#fdfa04;
opacity: 0.5;
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.thumb img{
position: absolute;
top: 0;
left: 0;
}
</style>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
window.onload = function(){
var box = $('zoomDiv');//normal是zoom的父节点,normal和thumb是兄弟节点
var normal = box.children[0];
var zoom = box.children[0].children[1];
var thumb = box.children[1];//这是找他的第二个孩子,box的第一个儿子是normal,第二个儿子是thumb
//先放鼠标,然后大图显示,离开,大图消失,放上去时黄色快随鼠标移动
normal.onmouseover = function(){
zoom.style.display = 'block';
thumb.style.display = 'block';
}
normal.onmouseout = function(){
zoom.style.display = 'none';
thumb.style.display = 'none';
}
var x = 0;
var y= 0;
normal.onmousemove = function(event){//这一块是防止黄块出去
var evt = event || window.event;
x = evt.clientX - this.parentNode.offsetLeft - zoom.offsetWidth / 2;
y = evt.clientY - this.parentNode.offsetTop - zoom.offsetHeight / 2;
if (x < 0) {
x = 0;
}else{
if (x > normal.offsetWidth - zoom.offsetWidth) {
x = normal.offsetWidth - zoom.offsetWidth;
}
}
if (y < 0) {
y = 0;
}else{
if (y > normal.offsetHeight - zoom.offsetHeight) {
y = normal.offsetHeight - zoom.offsetHeight;
}
}
//console.log(x + ':' + y);//比例是大图/小图,前两行是移动黄块的,中间两行是计算大图移动的像素的,后两行是移动大图的
zoom.style.left = x + 'px';
zoom.style.top = y + 'px';
var tX = -x * 800 / normal.offsetWidth;
var tY = -y *800 / normal.offsetHeight;
thumb.children[0].style.left = tX + 'px';
thumb.children[0].style.top = tY + 'px';
}
}
</script>
</head>
<body>
<div class="box" id="zoomDiv">
<div class="normal">
<img src="imgs/show.jpg" alt="">
<div class="zoom"></div>
</div>
<div class="thumb">
<img src="imgs/detail.jpg">
</div>
</div>
</body>
</html>