使用 Mkdocs 开发文档时,图片点击查看大图问题

3,463 阅读1分钟

MedusaSorcerer的博客

提要

在使用 Mkdocs 撰写静态说明文档网页的时候, 对于一些大图片的展示都是压缩的, 并且想查阅其中的内容的时候, 就要通过打开图片所在网址进行浏览, 直观的文档, 也可以给客户更好的体验。

所以本篇博文主要是实现点击图片后, 查看图片大图详情。

实现

在网页加载完成后, 给所有的 IMG 标签加载 onclick 属性:

window.onload = function () {
    for (let item of document.getElementsByTagName('img')) {
        if (item.classList.contains('pass') === false) {
            item.setAttribute('onclick', 'clickAction(this)');
        }
    }
}

点击图片的执行函数主要包含背景渲染以及图片加载, 并设置相关样式:

function clickAction(img) {
    let medusa = document.createElement('div');
    medusa.setAttribute('id', 'imgBaseDiv');
    medusa.setAttribute('onclick', 'closeImg()');
    let image = document.createElement('img');
    image.setAttribute('src', img.src);
    medusa.appendChild(image);
    document.body.appendChild(medusa);
}

背景 DIV 标签添加的监听函数仅删除当前 DIV, 起到关闭功能:

function closeImg() {
    document.getElementById('imgBaseDiv').remove();
}

CSS 样式:

#imgBaseDiv > img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-width: 99%;
    max-height: 99%;
}

#imgBaseDiv {
    width: 100%;
    height: 100%;
    position: fixed;
    background: rgba(0, 0, 0, 0.9);
    top: 0;
    left: 0;
    z-index: 1050;
}

需要注意的是, 在 Mkdocs 中有相关导入自定义 .css 文件的配置选项, 但没有导入相关自定义 .js 的配置选项, 所以当你需要实现导入自定义 .js 文件的时候, 需要在你的 .md 中增加以下代码行, 当然了, 你需要将 src 的属性值替换成你的路径:

<script src="static/doc.js"></script>

或者是你使用 Mkdocs 的时候, 使用你自己撰写的生成模板文件, 在模板文件中直接引入。



人生最终的价值在于觉醒和思考的能力,而不只在于生存。 --- 亚里士多德