版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36818386/article/details/82288136
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*
{
margin: 0px;
padding: 0px;
}
.box
{
position: relative;
width: 450px;
margin: 30px;
}
.fangda
{
position: absolute;
left: 0;
top: 0;
width: 225px;
height: 225px;
background-color: orange;
opacity: 0.5;
cursor: move;
display: none;
}
.box2
{
position: absolute;
left: 700px;
top: 20px;
width: 400px;
height: 400px;
background: url("images/big.jpg") no-repeat;
display: none;
}
img
{
display: block;
}
</style>
</head>
<body>
<div class="box">
<img src="images/small.jpg" alt="">
<div class="fangda"></div>
</div>
<div class="box2">
</div>
<script>
var box = document.querySelector(".box");
var fangda = document.querySelector(".fangda");
var box2 = document.querySelector(".box2");
//鼠标移上的时候
box.onmousemove = function (event)
{
fangda.style.display = "block";
box2.style.display = "block";
var x = event.pageX - box.offsetLeft;
var y = event.pageY - box.offsetTop;
//鼠标不可以移动,但是放大镜可以移动
var left = x - 225 / 2;
var top = y - 225 / 2;
if (left < 0)
{
left = 0;
}
else if (left > 225)
{
left = 225;
}
if (top < 0)
{
top = 0;
} else if (top > 225)
{
top = 225;
}
fangda.style.left = left + "px";
fangda.style.top = top + "px";
box2.style.backgroundPosition = - left * (400 / 225) + "px " + -top * (400 / 225) + "px";
};
//鼠标移除的时候
box.onmouseleave = function ()
{
fangda.style.display = "none";
box2.style.display = "none";
};
</script>
</body>
</html>