仿京东放大镜

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜2</title>
<style>
#box{
350px;
height: 350px;
border: 1px solid #ccc;
margin: 100px auto;
position: relative;
}
#big_box{
450px;
height: 450px;
border:1px solid #ccc;
position:absolute;
left: 360px;
top:0;
overflow: hidden;
display: none;
}
#big_box img{
position: absolute;
left: 0;
top:0;
}
#small_box{
position:relative;
}
#mask{
100px;
height: 100px;
font-weight:bold;">rgba(255,255,0,0.4);
position: absolute;
left:0;
top:0;
display: none;
cursor:move;
}
</style>
</head>
<body>
<div id="box">
<div id="small_box">
<img src="images/001.jpg">
<div id="mask"></div>
</div>
<div id="big_box">
<img src="images/0001.jpg">
</div>
</div>
</body>
<script>
var box = document.getElementById("box");
var small_box = box.children[0];
var mask = small_box.children[1];
var big_box = box.children[1];
small_box.onmouseover = function(){
mask.style.display = "block";
big_box.style.display = "block";
}
small_box.onmouseout = function(){
mask.style.display = "none";
big_box.style.display = "none";
}
//鼠标在小盒子中移动时,获取到遮罩盒子的坐标
var x = 0, y = 0;
small_box.onmousemove = function(event){
var event = event || window.event;
x = event.clientX - this.offsetParent.offsetLeft- mask.offsetWidth/2;
y = event.clientY - this.offsetParent.offsetTop - mask.offsetHeight/2;
//限制遮罩盒子不能走出小盒子
if(x < 0){
x = 0
}else if( x > small_box.offsetWidth - mask.offsetWidth){
x= small_box.offsetWidth - mask.offsetWidth
}if(y < 0){
y = 0
}else if(y > small_box.offsetHeight - mask.offsetHeight){
y = small_box.offsetHeight - mask.offsetHeight
}
mask.style.left = x + "px"
mask.style.top = y +"px";
// console.log(x);
//大盒子的图片跟着遮罩盒子动,根据比例关系大盒子图片走动的距离为 450/350 * 小盒子走动的距离
var big_image = big_box.children[0];
big_image.style.left = - big_image.offsetWidth / small_box.offsetWidth * x +"px"
big_image.style.top = - big_image.offsetHeight / small_box.offsetHeight * y +"px"
// console.log( big_image.style.left)
}
</script>
</html>
原文地址:https://www.cnblogs.com/zhaocong/p/7116966.html