摘要:我们平时逛网站的时候很普及的一个功能,有需要的小伙伴可以拿走
实现:css+html+js(图片也放在下面了,可以看一下呢)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.wapper .small {
position: relative;
}
.wapper .small,
.wapper .small>img {
/* 小放大镜和缩略图设置 */
width: 640px;
height: 400px;
}
.wapper .small>.mark {
/* 黄框的设置 */
width: 320px;
height: 200px;
background-color: yellow;
opacity: 0.5;
position: absolute;
top: 0;
display: none;
}
.wapper .big {
/* 大放大镜设置 */
width: 960px;
height: 600px;
overflow: hidden;
position: relative;
display: none;
}
/* 原图 */
.wapper .big>img {
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div class="wapper">
<!-- 小放大镜外框-->
<div class="small">
<img src="imgs/xhr.jpg">
<!-- 小放大镜,黄色的框框 -->
<div class="mark"></div>
</div>
<!-- 大放大镜框 -->
<div class="big">
<!-- 大放大镜原图 -->
<img src="imgs/xhr.jpg">
</div>
</div>
<script type="text/javascript">
//分别获取4个重要的dom节点。
var _small = document.querySelector(".small");
var _mark = document.querySelector(".mark");
var _big = document.querySelector(".big");
var _img = document.querySelector(".big>img");
//小放大镜移动事件
_small.onmousemove = function(e) {
var dx = e.pageX - _small.offsetLeft - _mark.offsetWidth / 2;
var dy = e.pageY - _small.offsetTop - _mark.offsetHeight / 2;
//给黄框定位,不让出来small当到左边的时候,让他们相等
if (dx <= 0) {
dx = 0;
}
//如果移动x轴的距离>=小放大镜的控件宽度-黄框的控件宽度,则让他们相等
if (dx >= _small.offsetWidth - _mark.offsetWidth) {
dx = _small.offsetWidth - _mark.offsetWidth;
}
// 黄框的左边坐标=鼠标的距离浏览器左上角的x轴-小放大镜框的x轴偏移量-黄框宽度的一半(鼠标在中间时候)
_mark.style.left = dx + 'px';
// 如果黄框到上面的时候让他们相等
if (dy <= 0) {
dy = 0;
}
//如果移动y轴的距离>=小放大镜的控件高度-黄框的控件高度,则让他们相等
if (dy >= _small.offsetHeight - _mark.offsetHeight) {
dy = _small.offsetHeight - _mark.offsetHeight;
}
// 黄框的上边坐标=鼠标的距离浏览器左上角的y轴-小放大镜框的y轴偏移量-黄框的高度的一半(鼠标在中间时候)
_mark.style.top = dy + 'px';
// 小框移动的同时,原图也反方向移动,移动的比例是小图缩放比例的倍数.我这里小图缩放了3倍,所以大图要×3倍
_img.style.left = -3 * dx + 'px';
_img.style.top = -3 * dy + 'px';
}
//小放大镜悬浮事件,当小放大镜悬浮的时候,把黄框和大图显示出来
_small.onmouseover = function() {
_mark.style.display = "block";
_big.style.display = "block";
}
//当鼠标离开小放大镜的时候,把黄框和大图都隐藏起来
_small.onmouseout = function() {
_mark.style.display = "none";
_big.style.display = "none";
}
</script>
</body>
</html>