点击图片居中放大显示,背景半透明遮罩,鼠标滚轮可缩放图片大小,再次点击图片恢复原始大小并关闭。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>图片点击放大居中+滚轮缩放</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
.zoom-img {
width: 200px;
cursor: pointer;
margin: 10px;
}
#imgZoomMask {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
z-index: 9999;
cursor: pointer;
}
/* 外层容器居中 */
.img-wrap {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 图片以中心点缩放 */
#imgZoomBox {
max-width: 90vw;
max-height: 90vh;
cursor: pointer;
transition: transform 0.15s ease;
display: block;
}
</style>
</head>
<body>
<img src="https://picsum.photos/id/10/800/800" class="zoom-img" alt="点击放大">
<img src="https://picsum.photos/id/20/600/900" class="zoom-img" alt="点击放大">
<div id="imgZoomMask">
<div class="img-wrap">
<img id="imgZoomBox" src="">
</div>
</div>
<script>
$(function() {
let scale = 1;
// 点击原图弹出
$(document).on('click', '.zoom-img', function() {
let src = $(this).attr('src');
scale = 1;
$('#imgZoomBox').attr('src', src).css('transform', `scale(${scale})`);
$('#imgZoomMask').fadeIn(200);
});
// 滚轮缩放
$('#imgZoomBox').on('wheel', function(e) {
e.preventDefault();
if (e.originalEvent.deltaY < 0) {
scale += 0.1;
} else {
scale -= 0.1;
}
// 缩放极值
scale = Math.max(0.3, Math.min(scale, 3));
$(this).css('transform', `scale(${scale})`);
});
// 点击遮罩/图片关闭
$('#imgZoomMask').click(function() {
$(this).fadeOut(200);
})
$('#imgZoomBox').click(function(e) {
e.stopPropagation();
$('#imgZoomMask').fadeOut(200);
})
});
</script>
</body>
</html> 本站原创内容,转载请注明来源:https://www.liutonghui.com/70
评论列表(0条)
暂无评论