<!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>
* {
margin: 0;
padding: 0;
}
.box {
width: 400px;
height: 400px;
position: relative;
}
.box img {
width: 100%;
height: 100%;
}
.box span {
display: none;
position: absolute;
left: 100px;
top: 0;
width: 200px;
height: 200px;
background: rgba(255, 255, 0, 0.2);
cursor: move;
}
.bigBox {
display: none;
position: absolute;
width: 400px;
height: 400px;
left: 420px;
top: 0px;
overflow: hidden;
}
.bigBox img {
position: absolute;
width: 800px;
height: 800px;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box">
<span></span>
<img src="./08.jpg" alt="">
</div>
<div class="bigBox">
<img src="./08.jpg" alt="">
</div>
<script>
var box = document.querySelector(".box"),
boxspan = document.querySelector(".box span"),
bigBox = document.querySelector(".bigBox")
images = document.querySelector(".bigBox img")
box.onmouseenter = function () {
boxspan.style.display = "block"
bigBox.style.display = "block"
}
box.onmouseleave = function () {
boxspan.style.display = "none"
bigBox.style.display = "none"
}
box.onmousemove = function (e) {
e = e || event
function getBoxPosition() {
// 计算盒子到整个文档边缘的坐标(包含滚动条)
// 先加上自己到offsetParent距离,然后再继续往上找,直到没有offsetParent为止
var position = { left: 0, top: 0 }
var ele = box
while (ele.offsetParent !== null) {
position.left += ele.offsetLeft
position.top += ele.offsetTop
// 每往前加一步就要变成父级继续累加
ele = ele.offsetParent
}
return position
}
var _left = e.pageX - getBoxPosition().left
var _top = e.pageY - getBoxPosition().top
// console.log(_left);
_left=_left-(boxspan.offsetWidth/2)
_top = _top-(boxspan.offsetHeight/2)
if (_left < 0) {
_left = 0
}
if (_top < 0) {
_top = 0
}
if (_left > box.offsetWidth - boxspan.offsetWidth) {
_left = box.offsetWidth - boxspan.offsetWidth
}
if (_top > box.offsetHeight - boxspan.offsetHeight) {
_top = box.offsetHeight - boxspan.offsetHeight
}
boxspan.style.top = _top + "px"
boxspan.style.left = _left + "px"
images.style.left = -2 * _left + "px"
images.style.top = -2 * _top + "px"
}
</script>
</body>
</html>
淘宝放大镜效果
最新推荐文章于 2022-09-18 10:37:31 发布