实现效果,如图所示:
主要用到了事件绑定,和位置计算的几个常用属性,clientX,clientY,offsetTop.offsetLeft(和定位配合使用)
下面是代码
<!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>
<style>
.small {
position: relative;
width: 350px;
height: 350px;
border: 1px solid #ccc;
float: left;
background-clip: padding-box;
cursor: pointer;
}
.big {
position: relative;
width: 540px;
height: 540px;
border: 1px solid #ccc;
float: left;
margin-left: 10px;
background-clip: padding-box;
overflow: hidden;
display: none;
}
.big>img {
position: absolute;
}
.small .move {
position: absolute;
top: 0;
left: 0;
background: rgba(200, 200, 50, 0.5);
border: 1px solid #999;
box-sizing: border-box;
cursor: move;
display: none;
}
</style>
</head>
<body>
<div class="small">
<img src="images/mouse.jpg" alt="">
<div class="move"></div>
</div>
<div class="big">
<img src="images/mouseBigSize.jpg" alt="">
</div>
<script src="index.js"></script>
</body>
<script>
var small = document.querySelector(".small");
var move = document.querySelector(".move");
var bigDiv = document.querySelector(".big")
var img = document.querySelector(".big>img")
small.onmouseenter = function() {
move.style.display = "block";
bigDiv.style.display = "block"
move.style.width = "200px";
move.style.height = "200px";
}
small.onmouseleave = function() {
move.style.display = "none";
bigDiv.style.display = "none"
}
small.onmousemove = function(e) {
//相对于容器的坐标
//鼠标可移动距离 = 鼠标可视窗口 - 盒子距离body的left和top - 内盒子的宽度和高度
var x = e.clientX - small.offsetLeft - move.offsetWidth / 2;
var y = e.clientY - small.offsetTop - move.offsetHeight / 2;
//如果鼠标在可视距离外,即e.clientX 或者 e.clientY为负数
x = x <= 0 ? 0 : x;
y = y <= 0 ? 0 : y;
//如果鼠标可移动距离大于 大盒子宽度 - 小盒子移动宽度,则让他只能为最大宽度或者高度移动
console.log(small.offsetWidth, move.offsetWidth)
if (x >= (small.offsetWidth - move.offsetWidth)) {
x = (small.offsetWidth - move.offsetWidth);
console.log("x的最大宽度---------------------------------------------")
}
if (y >= (small.offsetHeight - move.offsetHeight)) {
y = (small.offsetHeight - move.offsetHeight);
console.log("x的最大高度---------------------------------------------")
}
// console.log("此时的移动宽度" + x, "此时的移动高度" + y)
move.style.top = y + "px";
move.style.left = x + "px";
//img的展示的大小应该是黄色区域的倍数
//所以倍数为盒子的大小除黄色区域的大小
var numX = small.offsetWidth / move.offsetWidth;
var numY = small.offsetHeight / move.offsetHeight;
//img的展示的大小
var doubleX = move.offsetWidth * numX
var doubleY = move.offsetHeight * numY
img.style.width = doubleX;
img.style.height = doubleY;
//黄色距离大框的x和y
//img距离大框的边距*倍数
img.style.top = -(y * numY) + "px";
img.style.left = -(x * numX) + "px";
}
</script>
</html>
如果大家有什么更好的建议,欢迎回访!