<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0px;
margin: 0px;
}
#box {
width: 430px;
height: 430px;
margin: 100px;
position: relative;
}
#smallImage {
width: 100%;
height: 100%;
}
#move {
width: 220px;
height: 220px;
border: 1px solid red;
position: absolute;
top: 0px;
left: 0px;
display: none;
}
#bimg {
width: 430px;
height: 430px;
border: 1px solid red;
position: absolute;
left: 450px;
top: 0px;
overflow: hidden;
display: none;
}
#b_bimg {
width: 880px;
height: 880px;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div id="box">
<img src="img01.jpg" id="smallImage">
<div id="move"></div>
<div id="bimg">
<img src="img01.jpg" alt="" id="b_bimg">
</div>
</div>
<script>
var box = document.getElementById('box');
var move = document.getElementById('move');
var bimg = document.getElementById('bimg');
var b_bimg = document.getElementById('b_bimg');
//鼠标移入 移出
box.onmouseover = function() {
//遮挡层出现
move.style = 'display:block';
bimg.style = 'display:block';
}
box.onmouseout = function() {
move.style = "display:none";
bimg.style = "display:none"
}
//鼠标移动
box.onmousemove = function(e) {
var e = event || window.event;
//事件发生时 相对于视窗 y轴的距离
var y = e.clientY;
var x = e.clientX;
// console.log(y, x)
var t = box.offsetLeft;
var l = box.offsetTop;
// console.log(t, l)
var left = x - t - (move.offsetWidth) / 2;
var top = y - l - (move.offsetHeight) / 2;
if (top <= 0) {
top = 0;
} else if (top >= box.offsetHeight - move.offsetHeight) {
top = box.offsetHeight - move.offsetHeight
}
if (left <= 0) {
left = 0;
} else if (left >= box.offsetWidth - move.offsetWidth) {
left = box.offsetWidth - move.offsetWidth
}
move.style.left = left + 'px'
move.style.top = top + 'px';
//
// 计算比率
// 鼠标移动的距离 占 可移动距离 的 比例
// 3. 大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离
var w = left / (box.offsetWidth - move.offsetWidth);
var h = top / (box.offsetHeight - move.offsetHeight);
console.log(w, h, '比率')
var b_left = w * (b_bimg.offsetWidth - bimg.offsetWidth);
var b_top = h * (b_bimg.offsetHeight - bimg.offsetHeight);
b_bimg.style.left = -b_left + 'px';
b_bimg.style.top = -b_top + 'px'
}
</script>
</body>
</html>
模拟京东放大镜
最新推荐文章于 2024-07-06 16:47:02 发布