放大镜特效

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>放大镜效果</title>
</head>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}

img {
vertical-align: top;
}

#box {
width: 323px;
height: 420px;
margin: 20px;
position: relative;
}

#small_box {
width: 100%;
height: 100%;
border: 1px solid #ccc;
}

#small_box img {
width: 323px;
height: 420px;
}

#mask {
width: 100px;
height: 100px;
display: inline-block;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}

#big_box {
width: 451px;
height: 600px;
border: 1px solid #ccc;
overflow: hidden;
position: absolute;
top: 0;
left: 340px;
display: none;
}
#big_box img {
position: absolute;
top: 0;
left: 0;
}
</style>

<body>
<div id="box">
<div id="small_box">
<img src="images/pic001.jpg" alt="">
<span id="mask"></span>
</div>
<div id="big_box">
<img src="images/pic01.jpg" alt="">
</div>
</div>
</body>

</html>
<script>
window.onload = function () {
// 获取需要的标签
var box = document.getElementById("box");
var small_box = box.children[0];
var big_box = box.children[1];
var mask = small_box.children[1];
var big_img = big_box.children[0];
// 监听鼠标事件
small_box.onmouseover = function () {
// 2.1隐藏的盒子显示
mask.style.display = 'block';
big_box.style.display = 'block';

// 2.2监听鼠标移动

small_box.onmousemove = function (eevent) {
var e = event || Window.event;
var pointX = e.clientX - small_box.offsetParent.offsetLeft - mask.offsetWidth * 0.5;
var pointY = e.clientY - small_box.offsetParent.offsetTop - mask.offsetHeight * 0.5;
// 当黄色方块超出图片的位置时的操作
if( pointX < 0) {
pointX = 0;
} else if(pointX >= small_box.offsetWidth - mask.offsetWidth) {
pointX = small_box.offsetWidth - mask.offsetWidth
}
if( pointY < 0) {
pointY = 0;
} else if(pointY >= small_box.offsetHeight- mask.offsetHeight) {
pointY = small_box.offsetHeight - mask.offsetHeight
}
 
// 黄色方块的位置
mask.style.left = pointX + 'px';
mask.style.top = pointY + 'px';
// 大图和小图的比例
/*
smallX/bigX = 小盒子的宽度/大盒子的宽度
bigX = smallX(smallBox.width/大盒子的宽度)
*/
big_img.style.left = -(pointX / (small_box.offsetWidth / big_box.offsetWidth)) + 'px';
big_img.style.top = -(pointY / (small_box.offsetHeight / big_box.offsetHeight)) + 'px';

}
}
// 监听鼠标移出事件
small_box.onmouseout = function () {
mask.style.display = 'none';
big_box.style.display = 'none';
}
}
</script>
 
posted @ 2018-06-08 13:53  小小07  阅读(235)  评论(0编辑  收藏  举报