class Magnifier {
constructor(smallBox, bigBox) {
this.smallBox = smallBox
this.bigBox = bigBox
this.move = smallBox.querySelector('.move')
this.bigImg = bigBox.children[0]
this.init()
this.handlerMouse()
}
init() {
//计算对应的move这个盒子的宽高
// 大的比大的等于小的比小的 bigImg/bigBox = box/move ==> bigImg/box == bigBox/move
this.move.style.width = this.smallBox.clientWidth / (this.bigImg.clientWidth / this.bigBox
.clientWidth) + 'px'
this.move.style.height = this.smallBox.clientHeight / (this.bigImg.clientHeight / this.bigBox
.clientHeight) + 'px'
//先需要隐藏
this.move.style.display = 'none'
this.bigBox.style.display = 'none'
}
handlerMouse() {
//移入移出
this.smallBox.onmouseenter = () => {
this.move.style.display = 'block'
this.bigBox.style.display = 'block'
}
this.smallBox.onmouseleave = () => {
this.move.style.display = 'none'
this.bigBox.style.display = 'none'
}
//移动
this.smallBox.onmousemove = ({
pageX,
pageY
}) => {
//获取鼠标在smallbox里面位置
let currentX = pageX - this.smallBox.offsetLeft
let currentY = pageY - this.smallBox.offsetTop
//中心点位置
let centerPoint = {
x: this.smallBox.clientWidth / 2,
y: this.smallBox.clientHeight / 2
}
//移动的位置
let targetPoint = {
x: currentX - centerPoint.x,
y: currentY - centerPoint.y
}
//边界判断
if(targetPoint.x<0){
targetPoint.x = 0
}
if(targetPoint.y<0){
targetPoint.y = 0
}
//最大值判断
let maxPoint = {
x: this.smallBox.clientWidth - this.move.offsetWidth,
y: this.smallBox.clientHeight - this.move.offsetHeight
}
if(targetPoint.x > maxPoint.x){
targetPoint.x = maxPoint.x
}
if(targetPoint.y > maxPoint.y){
targetPoint.y = maxPoint.y
}
//设置对应的位置
this.move.style.left = targetPoint.x + 'px'
this.move.style.top = targetPoint.y + 'px'
//还要设置大盒子里面图片的位置
this.bigImg.style.left = -targetPoint.x * this.bigImg.clientWidth / this.smallBox.clientWidth + 'px'
this.bigImg.style.top = -targetPoint.y * this.bigImg.clientHeight / this.smallBox.clientHeight + 'px'
}
}
}
var small = document.querySelector('.box')
var big = document.querySelector('.bigbox')
new Magnifier(small, big)
标签:smallBox,style,效果,放大镜,move,bigBox,简单,bigImg,targetPoint
From: https://www.cnblogs.com/gujmnlk/p/16608374.html