<!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>Document</title>
<script src="js/common.js"></script>
<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;
}
.big img {
position: absolute;
}
.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.jpg" width="350" alt="" />
<div class="mask"></div>
</div>
<div class="big">
<img src="images/big.jpg" width="800" alt="" />
</div>
</div>
<script>
var box = my$('box');
var smallBox = box.children[0];
var bigBox = box.children[1];
var smallImage = smallBox.children[0];
var mask = smallBox.children[1];
var bigImage = bigBox.children[0];
// 1.鼠标移入,.mask 显示 ,大图显示; 当鼠标移除,隐藏
// mouseenter mouseleave 不会触发事件冒泡
// mouseover mouseout 会触发事件冒泡
box.onmouseenter = function () {
mask.style.display = 'block';
bigBox.style.display = 'block';
}
box.onmouseleave = function () {
mask.style.display = 'none';
bigBox.style.display = 'none';
}
//2.当鼠标在盒子中移动,让鼠标和盒子一起移动
box.onmousemove = function (e) {
e = e || window.event;
// 鼠标在盒子中位置,相当于mask在盒子中的位置
var maskX = getPage(e).pageX - box.offsetLeft;
var maskY = getPage(e).pageY - box.offsetTop;
// 让鼠标在mask中心
maskX = maskX - mask.offsetWidth / 2;
maskY = maskY - mask.offsetHeight / 2;
// 把mask限制在盒子中
maskX = maskX < 0 ? 0 : maskX;
maskY = maskY < 0 ? 0 : maskY;
maskX = maskX > box.offsetWidth - mask.offsetWidth ? box.offsetWidth - mask.offsetWidth : maskX;
maskY = maskY > box.offsetHeight - mask.offsetHeight ? box.offsetHeight - mask.offsetHeight : maskY;
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
// 3.当mask移动,大图跟着一起移动
// mask移动的距离/mask最大能移动的距离 = 大图片移动的距离/大图片最大能移动的距离
var maskMax = box.offsetHeight - mask.offsetHeight;
var bigImageMax = bigImage.offsetWidth - bigBox.offsetWidth;
var bigImageX = maskX * bigImageMax / maskMax;
var bigImageY = maskY * bigImageMax / maskMax;
bigImage.style.left = -bigImageX + 'px';
bigImage.style.top = -bigImageY + 'px';
}
</script>
</body>
</html>
放大镜效果
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...