原生js写的放大镜

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<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: 0;
left: 0;
cursor: move;
display: none;
}

.small {
position: relative;
}

img {
vertical-align: middle;
}
</style>
<script src="jquery-1.11.1-min.js"></script>
<script>
window.onload = function () {
var box = document.getElementById("box");
var small = box.getElementsByTagName("div")[0];
var mask = small.getElementsByTagName("div")[0];
var big = document.getElementById("big");
var bigImg = big.getElementsByTagName("img")[0];
small.onmouseenter = function () {
show(mask);
show(big);
}
small.onmouseleave = function () {
hide(mask);
hide(big);
}
small.onmousemove = function (event) {
event = event || window.event;
var pagey = event.pageY || scroll().top + event.clientY;
var pagex = event.pageX || scroll().left + event.clientX;
var smally = box.offsetTop;
var smallx = box.offsetLeft;
var y = pagey - smally - mask.offsetHeight/2;
var x = pagex - smallx - mask.offsetWidth/2;
if(x<0){
x = 0;
}
if(x>small.offsetWidth-mask.offsetWidth){
x=small.offsetWidth-mask.offsetWidth;
}
if(y<0){
y = 0;
}
if(y>small.offsetHeight-mask.offsetHeight){
y=small.offsetHeight-mask.offsetHeight;
}
mask.style.left = x + "px";
mask.style.top = y + "px";
var bili1 = bigImg.offsetWidth/small.offsetWidth;
var yy = bili1*y;
var xx = bili1*x;
bigImg.style.marginTop = -yy+"px";
bigImg.style.marginLeft = -xx+"px";
}
}
</script>
</head>
<body>
<div class="box" id="box">
<div class="small">
<img src="001.jpg" alt=""/>
<div class="mask"></div>
</div>
<div class="big" id="big">
<img src="0001.jpg" alt=""/>
</div>
</div>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/zaochenli/p/9220530.html