layer 图片预览自适应窗口

//html结构
<a href="javascript:;" onClick="showImg(this)" data-href="{$vo.src}" ><img src="{$vo.src}" class="img-responsive" ></a>


function showImg(obj){
    var url = $(obj).data('href');
    var thisimg = $(obj).siblings().find('img')
    var img = "<img src='" + url + "'  />";
    var setting = {
        type: 1,
        title: false,
        closeBtn: 0,
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        shade: 0.6, //遮罩透明度
        content: img
    }

    var windowH = $(window).height();
    var windowW = $(window).width();

    getImageWidth(url,function(w,h){
        //console.log("win:"+windowH+","+windowW);
        //console.log("img:"+h+","+w);
        // 调整图片大小
        if(w>windowW || h>windowH){
            if(w>windowW && h>windowH){
                w = thisimg .width()*3;
                h = thisimg .height()*3;
                setting.area = [w+"px",h+"px"];
            }else if(w>windowW){
                setting.area = [windowW+"px",windowW*0.5/w*h+"px"];
            }else{
                setting.area = [w+"px",windowH+"px"];
            }
        }else{
            setting.area = [w+"px",h+"px"];
        }
        // 设置layer
        layer.open(setting);
    });
}

function getImageWidth(url,callback){
    var img = new Image();
    img.src = url;

    // 如果图片被缓存,则直接返回缓存数据
    if(img.complete){
        callback(img.width, img.height);
    }else{
        // 完全加载完毕的事件
        img.onload = function(){
            callback(img.width, img.height);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qazx123q/article/details/82256930