<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#imgLeft {
width: 350px;
height: 350px;
position: absolute;
left: 20px;
top: 20px;
box-shadow: 20px 20px 30px 10px #444444;
}
#imgLeft img {
width: 350px;
height: 350px;
}
#imgLeft div#mark {
position: absolute;
width: 175px;
height: 175px;
cursor: move;
background-color: cornsilk;
opacity: .6;
display: none;
}
#imgRight {
width: 400px;
height: 400px;
position: absolute;
left: 390px;
top: 20px;
overflow: hidden;
display: none;
}
#imgRight img {
width: 800px;
height: 800px;
position: absolute;
}
</style>
</head>
<body style="height: 3000px;">
<div id="imgLeft">
<img src="./img/small.jpg" />
<!-- 遮罩层 -->
<div id="mark"></div>
<!-- 测试冒泡的 -->
<!-- <div id="center"></div> -->
</div>
<div id="imgRight">
<img src="img/big.jpg" />
</div>
<script>
//获取元素
var imgLeft = document.getElementById("imgLeft"),
mark = document.getElementById("mark");
var imgRight = document.getElementById("imgRight"),
aImg = imgRight.getElementsByTagName("img")[0];
// 三个状态
// onmouseenter onmousemove onmouseleave
// 鼠标移入先让mark显示 imgRight显示 然后确定mark的位置
imgLeft.onmouseenter = function (ev) {
// 事件对象的兼容处理
ev = ev || window.event;
// 让mark显示
mark.style.display = "block";
imgRight.style.display = "block"
// 确定位置
setPosition(ev);
}
// 移动过程中确定mark的位置
imgLeft.onmousemove = function (ev) {
// 事件对象的兼容处理
ev = ev || window.event;
// 确定位置
setPosition(ev);
}
// 隐藏mark
imgLeft.onmouseleave = function () {
// 隐藏mark
mark.style.display = "none";
imgRight.style.display = "none";
}
// 确定的位置的方法
function setPosition(ev) {
// 获取位置
var left = ev.clientX - imgLeft.offsetLeft - (mark.offsetWidth / 2);
var top = ev.clientY - imgLeft.offsetTop - (mark.offsetHeight / 2);
// 边界判断
var minLeft = 0,
maxLeft = imgLeft.offsetWidth - mark.offsetWidth;
var minTop = 0,
maxTop = imgLeft.offsetHeight - mark.offsetHeight;
if (left <= minLeft) {
left = minLeft;
} else if (left >= maxLeft) {
left = maxLeft;
}
if (top <= minTop) {
top = minTop;
} else if (top >= maxTop) {
top = maxTop;
}
//设置位置
mark.style.left = left + 'px';
mark.style.top = top + 'px';
// 确定的大图的位置
// 大图的宽度 / 小图的宽度 = 大图的可视区域 / 小图的可视区域(mark)
// 800 / 350 == 400 / 175
// 确定右边大图展示的比例
var ratioL = imgRight.clientWidth / mark.offsetWidth;
var ratioT = imgRight.clientHeight / mark.offsetHeight;
// 设置图片的位置
aImg.style.left = -ratioL * left + 'px';
aImg.style.top = -ratioT * top + 'px';
}
//onmouseenter 和 onmouseleave默认不冒泡
// center.onmouseenter = function(){
// console.log('center');
// }
// //状态 鼠标移入
// imgLeft.onmouseenter = function () {
// console.log('imgLeft');
// }
// document.body.onmouseenter = function () {
// console.log("body");
// }
// document.onmouseenter = function () {
// console.log("document");
// }
</script>
</body>
</html>
放大镜
最新推荐文章于 2021-06-15 13:36:35 发布