Typecho 实现大图功能
原生主题没有实现大图功能,再加上主题限制了文章宽度,一些大图看起来就很模糊,只能通过打开新的图片标签来查看大图,很不优雅。
网上搜了一下也有一些解决方案,例如使用FancyBox来实现灯箱功能,但是实际上目前来说我的博客没有用到太多图片展示,我所需要的仅仅是一个图片放大功能,有点杀鸡用牛刀的感觉。
所以经过一秒钟的考虑,决定手动用js实现一个简单的图片放大功能。
做法十分简单,只需要在footer.php
或者header.php
文件中增加以下代码:
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.post-content img').forEach(img => {
img.style.cursor = 'zoom-in'; // 提示可放大
img.addEventListener('click', function() {
// 创建遮罩层
const overlay = document.createElement('div');
overlay.className = 'lightbox-overlay';
// 创建图片容器
const content = document.createElement('div');
content.className = 'lightbox-content';
// 克隆图片并设置尺寸
const largeImg = new Image();
largeImg.src = this.src;
largeImg.style.cursor = 'zoom-out'; // 提示可关闭
// 计算最佳显示尺寸
function resizeImage() {
const maxWidth = window.innerWidth * 0.9;
const maxHeight = window.innerHeight * 0.9;
const ratio = Math.min(maxWidth / largeImg.naturalWidth,
maxHeight / largeImg.naturalHeight);
content.style.transform = `translate(-50%, -50%) scale(${ratio})`;
}
// 组合元素并显示
content.appendChild(largeImg);
overlay.appendChild(content);
document.body.appendChild(overlay);
// 初始化尺寸
resizeImage();
overlay.style.display = 'block';
// 关闭逻辑
const closeLightbox = () => {
overlay.remove();
};
// 点击图片关闭
largeImg.addEventListener('click', (e) => {
e.stopPropagation();
closeLightbox();
});
// 点击遮罩层关闭
overlay.addEventListener('click', closeLightbox);
// 按ESC关闭
document.addEventListener('keydown', function onEsc(e) {
if (e.key === 'Escape') {
closeLightbox();
document.removeEventListener('keydown', onEsc);
}
});
});
});
});
</script>
<style>
/* 遮罩层样式 */
.lightbox-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
z-index: 9999;
}
/* 图片容器 */
.lightbox-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 90vmin; /* 以视口最小边为基准 */
max-height: 90vmin;
}
/* 图片样式 */
.lightbox-content img {
width: 100%;
height: 100%;
object-fit: contain; /* 保持比例完整显示 */
cursor: pointer; /* 显示可点击光标 */
}
</style>
实现效果:
本文作者:masteren本文链接:https://blog.masteren.top/archives/35/ 版权声明:本文为原创内容,采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议(CC BY-NC-SA 4.0) 进行许可,转载时须注明出处并使用相同协议声明。