• 让图片在div盒子中水平垂直居中


    //调整多张图片,让图片水平垂直居中

    function adjustImg(){

    let imgDiv = document.getElementsByClassName("img");//找到img标签外面的class 名为img的div盒子

    for (let i = 0; i < imgDiv.length; i++){

    // console.log(i);

    let obj = imgDiv[i].getElementsByTagName("img")[0];

    if (obj.complete) {//确保图片已经加载完成

    let imgH = obj.offsetHeight;

    let imgW = obj.offsetWidth;

    let img_scale = imgW/imgH;

    let boxH = obj.parentNode.offsetHeight;

    let boxW = obj.parentNode.offsetWidth;

    let box_scale = boxW / boxH;

    // console.log("imgH="+imgH+" imgW="+imgW+" boxH="+boxH+" boxW="+boxW);

    if(box_scale > img_scale){

    obj.style.width = "100%";

    imgH = obj.offsetHeight;

    imgW = obj.offsetWidth;

    let h = (imgH-boxH)/2;

    obj.style.marginTop = -h + "px"; //确保图片垂直居中

    }else{

    obj.style.height = "100%";

    imgH = obj.offsetHeight;

    imgW = obj.offsetWidth;

    let w = (imgW-boxW)/2;

    obj.style.marginLeft = -w + "px";

    }

    } else {

    obj.onload = function(){

    let imgH = obj.offsetHeight;

    let imgW = obj.offsetWidth;

    let img_scale = imgW/imgH;

    let boxH = obj.parentNode.offsetHeight;

    let boxW = obj.parentNode.offsetWidth;

    let box_scale = boxW / boxH;

    // console.log("imgH="+imgH+" imgW="+imgW+" boxH="+boxH+" boxW="+boxW);

    if(box_scale > img_scale){

    obj.style.width = "100%";

    imgH = obj.offsetHeight;

    imgW = obj.offsetWidth;

    let h = (imgH-boxH)/2;

    obj.style.marginTop = -h + "px";

    }else{

    obj.style.height = "100%";

    imgH = obj.offsetHeight;

    imgW = obj.offsetWidth;

    let w = (imgW-boxW)/2;

    obj.style.marginLeft = -w + "px";

    }

    };

    // obj.style.height = "100%";

    // obj.style.margin = "0 auto";

    }

    }

    }

  • 相关阅读:
    这4点微不足道的改变,正在带我起飞
    “挑三拣四”地学一学Java I/O
    做到这3点,你也能成为一个高情商的人
    深入浅出一下Java的HashMap
    前端学习 -- Css -- 有序列表和无序列表
    Python 文件I/O
    python 模块
    python 函数
    Python 日期和时间
    python 字典
  • 原文地址:https://www.cnblogs.com/zwdeblog/p/9201393.html
Copyright © 2020-2023  润新知