layer.open 预览图片

先上效果图:

HTML:

<img src="http://127.0.0.1/img/test.jpg" onclick="scanImg(this)" />

第一种:非动态赋值图片信息的, 只需要创建图片对象获取到实际宽高。或者重新固定图片宽高即可。

function scanImg(obj){
           let realpath = obj.src; // url地址
           let imgHtml = "<img src='"+ realpath +"' />";
           let img = new Image(); //Image对象
           img.src = realpath;
           let width = img.width,
                    height = img.height;
           layer.open({
                    type:1, // 类型是1
                    shade:0.2,
                    offset:'auto',
                    area:[width + 'px', height + 'px'],
                    shadeClose:true,
                    scrollbar: false,
                    title: '', // 这里不要写文字
                    content:imgHtml,
           });        
}    

第二种:动态赋值的,可能会遇到第一次点击预览图片,无法获取到图片宽高等信息的情况,所以要用 img.onload 等图片加载完

function scanImg(obj){
            let realpath = obj.src; // url地址
            let imgHtml = "<img src='"+ realpath +"' />";
            let img = new Image(); // Image对象

            img.onload = function () { // 重点:要用onload加载
                let width = img.width,
                    height = img.height;
                layer.open({
                    type:1, // 类型是1
                    shade:0.2,
                    offset:'auto',
                    area:[width + 'px', height + 'px'],
                    shadeClose:true,
                    scrollbar: false,
                    title: '', // 这里不要写文字
                    content:imgHtml,
                });
            };

            img.src = realpath;   
}

另外,如果用 $(this).src 获取的图片信息都是第一次的, 不妨用 attr 这个 $(this).attr('src') 试试获取!!

 

posted @ 2021-01-22 13:59  一粒小米-博客  阅读(1319)  评论(0编辑  收藏  举报