前言
最近在网上发现了一个放大镜效果,感觉很有意思。最终在b站找到了实现的教程。教程作者 xiao-high
教程链接点此查看
视频教程是基于html、css、js进行制作的。代码是我跟着教程手敲的。
效果图
原生版
<!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>
</head>
<style>
body {
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 500px;
height: 400px;
border: 1px solid red;
position: relative;
}
.move {
width: 150px;
height: 150px;
border: 2px solid black;
/* 设置圆圈 */
border-radius: 50%;
/* 初始透明度为0 */
opacity: 0;
/* 设置位置,放到图片上,父级相对定位,子级决定定位 */
position: absolute;
left: 0;
top: 0;
/* 圆圈溢出的图片部分隐藏 */
overflow: hidden;
}
.img {
width: 500px;
height: 400px;
}
/* 设置图片与圆圈的位置关系 */
.move img {
position: absolute;
left: 0;
top: 0;
}
</style>
<script>
//dom元素加载完成后,给dom元素添加事件
window.onload = function () {
//获取元素对象
let container = document.querySelector('.container');
let move = document.querySelector('.move')
let bigImg = document.querySelector('.move img')
//鼠标移入事件
container.addEventListener('mousemove', function (e) {
/***********圆圈处理****************************/
//设置鼠标小手的样式,将鼠标小手隐藏
move.style.cursor = 'none'
//设置圆圈透明度,移入显示
move.style.opacity = 0.6
/******处理圆圈在小图内的移动************************/
//获取鼠标位置
let x = e.clientX
let y = e.clientY
//获取容器左边和上边的偏移量
let left = container.offsetLeft
let top = container.offsetTop
//计算鼠标在容器上的移动距离。这里还要减去圆的半径,保证鼠标在圆的中心
let moveX = x - left - move.offsetWidth / 2
let moveY = y - top - move.offsetHeight / 2
//边界处理,不让放大镜移出
if (moveX <= 0) {
moveX = 0
}
//最大水平值获取
let maxMoveX = container.offsetWidth - move.offsetWidth
if (moveX >= maxMoveX) {
moveX = maxMoveX
}
if (moveY <= 0) {
moveY = 0
}
//最大垂直值获取
let maxMoveY = container.offsetHeight - move.offsetHeight
if (moveY >= maxMoveY) {
moveY = maxMoveY
}
//设置圆圈的移动
move.style.left = moveX + 'px'
move.style.top = moveY + 'px'
/***********处理圆圈内图片的移动*****************/
//圆圈相对于小图移动,大图相对于圆圈移动。如果圆圈往右移动,大图要往左移动
//大图移动的距离
let bigX = (moveX + move.offsetWidth / 2) / container.offsetWidth * bigImg.offsetWidth - move.offsetWidth / 2
//移动大图
bigImg.style.left = -bigX + 'px'
//大图移动的距离
let bigY = (moveY + move.offsetHeight / 2) / container.offsetHeight * bigImg.offsetHeight - move.offsetHeight / 2
//移动大图
bigImg.style.top = -bigY + 'px'
})
//鼠标移出事件
container.addEventListener('mouseout', function () {
//设置圆圈透明度,移出隐藏
move.style.opacity = 0
})
}
</script>
<body>
<div class="container">
<!-- 看到的图片 -->
<img src="./image/b.jpg" alt="图片" class="img" />
<!-- 这个div是放大镜 -->
<div class="move">
<!-- 放大镜,圆圈里看到的图片 -->
<img src="./image/b.jpg" alt="图片" />
</div>
</div>
</body>
</html>
备注:
1、图片的尺寸要够大,我用的这个图片是4k的,分辨率太小,图片放大会模糊。
2、放大镜的透明的我设置的是0.6,从图中可以看到还可以看到原图。如果不想看到放大那部分的原图,透明度可以设置为0