zoukankan      html  css  js  c++  java
  • 让图片在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";

    }

    }

    }

  • 相关阅读:
    对百度搜索引擎的评论
    团队开发个人总结05
    Bootsrap下拉菜单实现Hover下拉效果
    C#抽奖优惠券生成唯一码方法
    js.live方法无效, 报错:uncaught TypeError: $(...).live is not a function
    SQL 插入一条自定义主键值的数据
    一款很简单的直接发送邮件功能
    SQL生成指定范围内随机值
    SQL(replace)替换字段中指定的字符
    SQL表中删除一列
  • 原文地址:https://www.cnblogs.com/zwdeblog/p/9201393.html
Copyright © 2011-2022 走看看