100多行代码实现js或者jquery版的类似juejin的预览图片功能

1,187 阅读4分钟

前言

预览图片是一个很常用的业务功能,比如掘金的预览图片功能,下面我们就来模拟实现一个类似掘金的简单预览图片功能(PS:最终实现动画效果不如掘金,可自行扩展,还有就是嵌套的元素与掘金的方式也有区别)。

创建一个构造函数

首先新建一个js文件,命名为viewer.js,然后在这个js文件中,我们来创建一个函数,命名为ewViewer。然后参数是一个图片元素,可以是jquery的图片元素,也可以是js dom图片元素,我们做一个判断然后分别调用不同的实现方法,如下所示:

function ewViewer(el){
    //判断页面内容是否存在jquery并且传入的el元素是否是一个jquerydom云阿苏
    if(typeof window.jQuery !== 'undefined' && el instanceof window.jQuery){
        this.previewjQuery(el);
    }else{
        this.previewJS(el);
    }
    return this;
}

实现js的预览图

实现的思路就是放置两个元素,第一个是遮罩层元素,并且设置相关的样式,子元素就是存放图片的元素,我们通过设置子元素的background-image属性来显示图片,代码如下(每一步的注释都解释了):

ewViewer.prototype.previewJS = function(el){
    const isDom = function(e){
        return typeof HTMLElement === 'object' ? e instanceof HTMLElement : e && typeof e === 'object' && e.nodeType === 1 && typeof e.nodeName === 'string' || e instanceof HTMLCollection || e instanceof NodeList;
    }
    // 如果传入的不是一个dom元素则不执行后续代码
    if(!isDom(el))return;
    const curElement = document.querySelector('#preview-img-mask');
    // 判断当前遮罩层元素是否存在
    if(!curElement){
        // 创建遮罩层元素
        const element = document.createElement('div');
        // 克隆一个节点
        const child = element.cloneNode(true);
        element.id = "preview-img-mask";
        // 添加遮罩层元素样式
        element.style.cssText += `position:fixed;left:0;top:0;right:0;display:none;z-index:10000;overflow:auto;width:100%;height:100%;background:rgba(0,0,0,0.5)`;
        // 子元素添加样式
        child.style.cssText += `background-repeat: no-repeat;background-position: center;background-size: contain;`;
        element.appendChild(child);
        document.body.appendChild(element);
    }
    // 重新获取遮罩层元素
    const maskLayer = document.querySelector('#preview-img-mask');
    // 判断如果传入的元素不是一个图片元素则不执行如下代码
    if (el.length || el.tagName.toLowerCase().indexOf('img') === -1)return;
    // 获取图片的原始宽高
    var imgNaturalWidth = el.naturalWidth,
        imgNaturalHeight = el.naturalHeight;
    // 移动端以及页面缩放做判断
    const isMobile = window.navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i);
    // 获取页面宽度
    const pageWidth = (function(){
        return window.innerWidth;
    })();
    // 如果当前页面宽度小于600,或是移动端设备,则将原始宽高缩放0.6倍
    if (isMobile || pageWidth <= 600) {
        imgNaturalWidth = imgNaturalWidth * 0.6;
        imgNaturalHeight = imgNaturalHeight * 0.6;
    }
    // 获取页面宽高
    var viewportWidth = window.innerWidth,
        viewportHeight = window.innerHeight;
    // 获取图片元素的src路径
    var imgUrl = el.getAttribute('src');
    // 显示遮罩层
    setTimeout(() => {
        maskLayer.style.display = "block";
    },600);
    // 获取遮罩层的子元素
    var maskLayerDiv = maskLayer.querySelector('div');
    // 设置子元素的样式
    maskLayerDiv.style.cssText += `background-image:url('${imgUrl}');background-size:${imgNaturalWidth}px ${imgNaturalHeight}px;width:0;height:0;`;
    // 判断图片宽度是否大于页面宽度,然后设置子元素的宽度
    if (imgNaturalWidth > viewportWidth) {
        maskLayerDiv.style.width = imgNaturalWidth + "px";
    } else {
        maskLayerDiv.style.width = "100%";
    }
    // 判断图片高度是否大于页面高度,然后设置子元素的高度
    if (imgNaturalHeight > viewportHeight) {
        maskLayerDiv.style.height = imgNaturalHeight + "px";
    } else {
        maskLayerDiv.style.height = "100%";
    }
    // 点击遮罩层关闭预览
    maskLayer.onclick = function(){
        setTimeout(() => {
            this.style.display = 'none';
        },600);
    }
}

实现jquery版

实现思路类似js版本,只不过是有些代码做了变换而已。

ewViewer.prototype.previewjQuery = function(el){
    const curElement = $('#preview-img-mask');
    // 判断如果页面不存在遮罩层元素,则添加该元素
    if (!curElement.length) {
        $(`<div id="preview-img-mask"><div></div></div>`).appendTo("body");
    }
    // 获取遮罩层元素
    var maskLayer = $('#preview-img-mask');
    // 设置遮罩层样式
    maskLayer.css({
        position:'fixed',
        left:0,
        top:0,
        right:0,
        display:'none',
        'z-index':10000,
        overflow:'auto',
        width:'100%',
        height:'100%',
        background:'rgba(0,0,0,0.5)'
    });
    // 判断传入的如果不是一个img元素
    if (el.prop('tagName').toLowerCase().indexOf('img') === -1)return;
    var imgNaturalWidth = el[0].naturalWidth,
        imgNaturalHeight = el[0].naturalHeight;
     // 移动端以及页面缩放做判断
     const isMobile = window.navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i);
     // 获取页面宽度
     const pageWidth = (function(){
         return $(window).width();
     })();
    //  判断页面宽度是否小于600以及是否是移动端
    if (isMobile || pageWidth <= 600) {
        imgNaturalWidth = imgNaturalWidth * 0.6;
        imgNaturalHeight = imgNaturalHeight * 0.6;
    }
    // 获取页面的宽高
    var viewportWidth = $(window).width(),
        viewportHeight = $(window).height();
    // 获取图片的路径
    var imgUrl = el.attr('src');
    maskLayer.fadeIn(600);
    // 获取子元素
    var maskLayerDiv = maskLayer.children();
    // 设置子元素样式
    maskLayerDiv.css({
        "background-image": "url(" + imgUrl + ")",
        "background-size": imgNaturalWidth + "px " + imgNaturalHeight + "px",
        "width": "",
        "height": "",
        "background-repeat": "no-repeat",
        "background-position": "center",
        "background-size": "contain"
    });
    // 判断图片原始宽高与页面宽高,从而决定子元素的宽高
    if (imgNaturalWidth > viewportWidth) {
        maskLayerDiv.css('width', imgNaturalWidth);
    } else {
        maskLayerDiv.css('width', '100%');
    }
    if (imgNaturalHeight > viewportHeight) {
        maskLayerDiv.css('height', imgNaturalHeight);
    } else {
        maskLayerDiv.css('height', '100%');
    }
    // 点击遮罩层关闭
    maskLayer.off("click").on("click", function () {
        $(this).fadeOut(600);
    });
}

调用方式

而且我们还做了判断,在移动端设备以及页面宽度小于600px的时候,我们将按照原图的宽高比例缩放0.6倍显示。调用方式也很简单,如以下一个示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预览图</title>
</head>
<body>
    <img src="/static/image/1.jpg" alt="">
    <img src="/static/image/1.jpg" alt="">
</body>
<script src="./viewer.js"></script>
<script src="./static/plugin/jquery.min.js"></script>
<script>
    //js方式调用代码如下:
    // let imgElements = document.querySelectorAll('img');
    // [].slice.call(imgElements).forEach((img) => {
    //     img.onclick = function(){
    //         const viewer = new ewViewer(this);
    //         console.log(viewer);
    //     }
    // });
    //jquery调用方式代码如下
    $('img').click(function(){
        const viewer = new ewViewer($(this));
        console.log(viewer);
    });
</script>
</html>

最后

这只是实现简单预览图的第一步,如果可以,还可以在这上面扩展,进而实现viewer.js那样的预览图片库了。不过本文旨在介绍简单的预览功能,后续就不赘述了。