发表于: 2023-03-07 20:05:56
0 242
放大镜效果练习:
<!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>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
left: 180px;
top: 100px;
}
.box img {
width: 400px;
height: 300px;
border: 1px solid cadetblue;
vertical-align: bottom;
}
.nav {
display: none;
width: 480px;
height: 360px;
border: 1px solid red;
background-image: url("../../js2-DOM/images/1.jpg");
background-size: 250% 250%;
position: absolute;
left: 582px;
top: 100px;
}
.small {
width: 160px;
height: 120px;
position: absolute;
/*background-color: black;*/
/*opacity: 0.5;*/
cursor: move;
}
</style>
</head>
<body>
<div class="box">
<div class="small"></div>
<img src="../../js2-DOM/images/1.jpg" alt="">
</div>
<div class="nav"></div>
<script>
//获取元素
//小盒子
let box = document.querySelector(".box");
//放大镜
let small = document.querySelector(".small");
//大盒子
let nav = document.querySelector(".nav");
box.onmousemove = function (client) {
let x = client.clientX - box.offsetLeft;
let y = client.clientY - box.offsetTop;
small.style.left = x - 80 + 'px';
small.style.top = y - 60 + 'px';
let dis_x = box.offsetLeft + box.offsetWidth - client.clientX;
let dis_y = box.offsetTop + box.offsetHeight - client.clientY;
nav.style.backgroundPositionX = (80 - x) * 3 + 'px';
nav.style.backgroundPositionY = (60 - y) * 3 + 'px';
if (x - 80 < 0) {
small.style.left = 0;
nav.style.backgroundPositionX = 0;
}
if (dis_x <= 80) {
small.style.left = box.offsetWidth - 160 + 'px';
nav.style.backgroundPositionX = (160 - box.offsetWidth) * 3 + 'px';
}
if (y - 60 < 0) {
small.style.top = 0;
nav.style.backgroundPositionY = 0;
}
if (dis_y < 60) {
small.style.top = box.offsetHeight - 120 + 'px';
nav.style.backgroundPositionY = (120 - box.offsetHeight) * 3 + 'px';
}
small.style.backgroundColor = "rgba(135, 207, 235, 0.61)";
}
small.addEventListener('mouseover', function () {
nav.style.display = 'block'
})
small.addEventListener('mouseout', function () {
nav.style.display = 'none'
small.style.backgroundColor="transparent"
})
</script>
</body>
</html>
评论