<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 350px;
height: 350px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
/*display: none;*/
}
.mask {
width: 175px;
height: 175px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0px;
left: 0px;
cursor: move;
display: none;
}
.small {
position: relative;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small"><!--小层-->
<img src="images/small.png" width="350" alt=""/>
<div class="mask"></div><!--遮挡层-->
</div><!--小图-->
<div class="big"><!--大层-->
<img src="images/big.jpg" width="800" alt=""/><!--大图-->
</div><!--大图-->
</div>
<!--导入外部的js文件-->
<!--<script src="common.js"></script>-->
<script>
function my$(id) {
return document.getElementById(id)
}
var small = my$("box").children[0]; //小图
var big = my$("box").children[1]; //大层
var mask = small.children[1]; //遮挡层
var bigImg = big.children[0]; //大图
my$("box").onmouseover = function () {
big.style.display = "block";
mask.style.display = "block";
};
my$("box").onmouseout = function () {
big.style.display = "none";
mask.style.display = "none";
}
small.onmousemove = function (e) {
var x = e.clientX - parseInt(mask.offsetWidth / 2); //获取鼠标横坐标-遮罩层的宽度一半
var y = e.clientY - parseInt(mask.offsetHeight / 2);//获取鼠标纵坐标-遮罩层高度一半
x = x - 100; //小图的margin值
y = y - 100;//小图的margin值
x = x <= 0 ? 0 : x; //横坐标最小值
y = y <= 0 ? 0 : y; //总坐标最小值
x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x; //横坐标最大值
y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y; //纵坐标最大值
mask.style.left = x + "px";
mask.style.top = y + "px";
//小图的移动距离/大图的移动距离====小图的最大移动距离/大图的最大移动距离
//大图的移动距离======小图的移动距离*大图的最大移动距离/小图的最大移动距离
//大图的横向移动距离
console.log(bigImg.offsetWidth - big.offsetWidth)
var bigx = x * (bigImg.offsetWidth - big.offsetWidth) / (small.offsetWidth - mask.offsetWidth);
var bigy = y * (bigImg.offsetHeight - big.offsetHeight) / (small.offsetHeight - mask.offsetHeight);
//大图的纵向移动距离
bigImg.style.marginLeft = -bigx + "px";
bigImg.style.marginTop = -bigy + "px";
}
</script>
</body>
</html>
网友评论