放大镜
<!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>
.small-box {
width: 200px;
height: 200px;
background-image: url(img/tou8.png);
background-size: 200px 200px;
position: absolute;
top: 100px;
left: 200px;
}
.mask {
width: 100px;
height: 100px;
background-color: red;
opacity: 0.3;
position: absolute;
display: none;
}
.big-box {
width: 400px;
height: 400px;
position: absolute;
left: 450px;
top: 100px;
background-image: url(img/tou8.png);
background-size: 800px 800px;
display: none;
}
ul {
width: 200px;
height: 50px;
position: absolute;
top: 300px;
left: 200px;
padding-left: 0;
margin: 0;
}
li {
list-style: none;
width: 40px;
height: 40px;
float: left;
background-color: yellowgreen;
background-size: 40px;
}
</style>
</head>
<body>
<div class="small-box">
<div class="mask"></div>
</div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="big-box"></div>
</body>
</html>
<script src="放大镜.js"></script>
<script>
let oSb = document.querySelector(".small-box");
let oM = document.querySelector(".mask");
let oBb = document.querySelector(".big-box");
let oUl = document.querySelector("ul");
let oLi = document.getElementsByTagName("li");
let b = new BF(oSb, oM, oBb, oUl, oLi);
</script>
class BF {
constructor(osb, om, obb, oul, oli) {
this.oSb = osb;
this.oM = om;
this.oBb = obb;
this.oUl = oul;
this.oLi = oli;
this.eventBind();
}
mouseover() {
let that = this;
this.oSb.onmouseover = function () {
that.oM.style.display = "block";
that.oBb.style.display = "block";
}
}
mouseout() {
let that = this;
this.oSb.onmouseout = function () {
that.oM.style.display = "none";
that.oBb.style.display = "none";
}
}
mousemove() {
let that = this;
this.oSb.onmousemove = function (evt) {
var e = evt || event;
let left = e.pageX - that.oM.offsetWidth / 2 - this.offsetLeft;
let top = e.pageY - that.oM.offsetHeight / 2 - this.offsetTop;
if (left < 0) {
left = 0
}
if (top < 0) {
top = 0
}
let maxLeft = that.oSb.offsetWidth - that.oM.offsetWidth;
if (left > maxLeft) {
left = maxLeft;
}
let maxTop = that.oSb.offsetHeight - that.oM.offsetHeight;
if (top > maxTop) {
top = maxTop;
}
let n = that.oBb.offsetWidth / that.oM.offsetWidth;
let x = n * left;
let y = n * top;
that.oBb.style.backgroundPositionX = -x + "px";
that.oBb.style.backgroundPositionY = -y + "px";
that.oM.style.left = left + "px";
that.oM.style.top = top + "px";
}
}
mouseoverLi() {
let that = this;
for (let i = 0; i < this.oLi.length; i++) {
this.oLi[i].style.backgroundImage = `url(img/${i}.jpg)`;
this.oLi[i].onmouseover = function () {
that.oSb.style.backgroundImage = `url(img/${i}.jpg)`;
that.oBb.style.backgroundImage = `url(img/${i}.jpg)`;
}
}
}
eventBind() {
this.mouseover();
this.mousemove();
this.mouseout();
this.mouseoverLi();
}
}