js原生放大镜
body体里的代码
<div class="left"> //左边的大div
<img src="./images/dali.jpg" width="100%" height="100%">
<div class="mask"></div> //放大镜的小块
</div>
<div class="right"> //右边的大div
<img src="./images/dali.jpg">
</div>
css样式代码
//给左右两个div设置样式
.left, .right{
width: 340px;
height: 500px;
border:1px solid red;
float:left;
margin-right:70px;
position: relative;
}
//让右边的图片超出隐藏
//最开始默认不显示,当鼠标进入才让他显示
.right {
overflow: hidden;
display: none;
}
//放大镜的样式
//默认不显示,鼠标进入显示
.mask {
width: 50px;
height: 50px;
background-color: rgba(0,0,255,0.5);
position: absolute;
left:0px;
top:0px;
display: none;
}
一定要给放大镜设置定位属性,放大镜的移动原理就是利用,定位后修改他的top和left的值。
js代码
window.onload = function(){ //等页面加载完在执行js代码,防止图片没有加载好获取不到值
// 获取元素节点
let leftDiv = document.querySelector('.left')
let mask = document.querySelector('.mask')
let rightDiv = document.querySelector('.right')
let bigImg = document.querySelector('.right img')
// 2.小色块跟随鼠标移动
leftDiv.onmousemove = function(e){
let x = 0
let y = 0
if (e.target == mask) {
x = e.offsetX + mask.offsetLeft
y = e.offsetY + mask.offsetTop
} else {
x = e.offsetX
y = e.offsetY
}
// 让鼠标显示在色块中心
x = x - mask.offsetWidth/2
y = y - mask.offsetHeight/2
// 防止坐标超出边界
let maxLeft = leftDiv.offsetWidth - mask.offsetWidth
if (x < 0) {
x = 0
} else if (x > maxLeft) {
x = maxLeft
}
let maxTop = leftDiv.offsetHeight - mask.offsetHeight
if (y < 0) {
y = 0
} else if (y > maxTop) {
y = maxTop
}
mask.style.left = x + 'px'
mask.style.top = y + 'px'
// 左边横向移动的百分比
let perX = - x / leftDiv.offsetWidth * 100 + '%'
// 左边坚向移动的百分比
let perY = - y / leftDiv.offsetHeight * 100 + '%'
// console.log(perX,'----',perY)
bigImg.style.transform = `translate(${perX},${perY})`
}
// 3.鼠标移入和移出
leftDiv.onmouseenter = function(){
mask.style.display = 'block'
rightDiv.style.display = 'block'
// 1.计算小色块尺寸
let w = leftDiv.offsetWidth * rightDiv.offsetWidth / bigImg.offsetWidth
let h = leftDiv.offsetHeight * rightDiv.offsetHeight / bigImg.offsetHeight
mask.style.width = w + 'px'
mask.style.height = h + 'px'
}
leftDiv.onmouseleave = function(){
mask.style.display = 'none'
rightDiv.style.display = 'none'
}
}