<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滚轮缩放图片演示</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.image-container {
position: relative;
overflow: hidden;
border: 2px solid #333;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
#zoomable-image {
display: block;
transition: transform 0.1s ease;
transform-origin: center center;
}
.info {
position: absolute;
bottom: 10px;
left: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 14px;
}
.credit {
position: fixed;
bottom: 10px;
right: 10px;
color: #666;
font-size: 12px;
}
</style>
</head>
<body>
<div class="image-container">
<img id="zoomable-image" src="https://picsum.photos/800/500" alt="可缩放图片">
<div class="info">使用鼠标滚轮缩放图片</div>
</div>
<script>
$(document).ready(function() {
const $image = $('#zoomable-image');
let scale = 1;
const minScale = 0.5;
const maxScale = 3;
const scaleStep = 0.1;
// 初始化图片尺寸
$image.on('load', function() {
$(this).data('original-width', $(this).width());
$(this).data('original-height', $(this).height());
});
// 滚轮事件处理
$image.on('wheel', function(e) {
e.preventDefault();
// 计算缩放方向
const delta = e.originalEvent.deltaY > 0 ? -1 : 1;
// 计算新缩放比例
let newScale = scale + (delta * scaleStep);
// 限制缩放范围
newScale = Math.max(minScale, Math.min(maxScale, newScale));
// 如果缩放比例有变化
if (newScale !== scale) {
scale = newScale;
// 应用缩放变换
$(this).css('transform', `scale(${scale})`);
// 更新容器尺寸以防止内容溢出
const originalWidth = $(this).data('original-width');
const originalHeight = $(this).data('original-height');
$(this).parent().css({
width: originalWidth * scale,
height: originalHeight * scale
});
// 显示当前缩放比例
$('.info').text(`缩放比例: ${Math.round(scale * 100)}%`);
}
});
// 双击重置缩放
$image.on('dblclick', function() {
scale = 1;
$(this).css('transform', 'scale(1)');
const originalWidth = $(this).data('original-width');
const originalHeight = $(this).data('original-height');
$(this).parent().css({
width: originalWidth,
height: originalHeight
});
$('.info').text('缩放已重置 (100%)');
});
});
</script>
</body>
</html>
滚轮缩放图片演示
于 2025-05-14 13:15:19 首次发布