2015-12-24 65 views
2

我想,以填補我的形象,同時保持長寬比(填寫), 這是它目前的外觀(背景顏色是我的div) image如何做方面填寫img標籤?

這是我的CSS

.img_model{ 
    height: 100%; 
    width: 100%; 
    object-fit: contain; 
} 
.square img.wide { 
    max-width: 100%; 
    max-height: 100%; 
    height: auto; 
} 
.square img.tall { 
    max-height: 100%; 
    max-width: 100%; 
    width: auto; 
} 

js代碼

$('.img_model').loadImages({ 
    imgLoadedClb: function(){}, 
    allLoadedClb: function(){}, 
    imgErrorClb: function(){}, 
    noImgClb:  function(){}, 
    dataAttr:  'src' 
}); 

$(window).load(function(){ 
$('.square').find('img').each(function(){ 
    var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall'; 
    $(this).addClass(imgClass); 
}) 
}); 

這是我如何在Java腳本創建的div

while(i<=22) 
    { 
     if(!document.getElementById('timedrpact'+i)) 
     { 
      var ele = document.createElement("div"); 
      ele.setAttribute("id","timedrpact"+i); 
      ele.setAttribute("class","col-sm-6 col-md-4 box portfolio-item square"); 
      ele.setAttribute("style","background-color:"+arr[i]); 
      output.appendChild(ele); 

      var ele = document.createElement("a"); 
      ele.setAttribute("id","a"+i); 
      ele.setAttribute("class","a_square"); 
      ele.setAttribute("href","www.google.com"); 
      ele.setAttribute("target","_self"); 
      ele.setAttribute("style","text-decorartion:none"); 
      document.getElementById("timedrpact"+i).appendChild(ele); 

      var ele = document.createElement("img"); 
      ele.setAttribute("id","img"+i); 
      ele.setAttribute("class","img_model"); 
      ele.setAttribute("style","width:100%;height:auto;"); 
      ele.setAttribute("src","http://luteciamodels.com/wp-content/uploads/2015/09/3_model_77997_3840x2160.jpg"); 
      document.getElementById("a"+i).appendChild(ele); 
     } 
     i++; 


    } 
像綠圈這個第一圖像

上午期待輸出.... 請幫助我 image

+1

如果你正在使用'object-fit',爲什麼不使用'object-fit:cover'來獲取圖像來填充容器? –

+0

@MarkM使它成爲答案,所以我可以接受,其工作很好 – Bangalore

+0

謝謝@Bangalore –

回答

1

Object-fit: cover將填充容器而不扭曲圖像。

+0

感謝它的工作原理酷 – Bangalore

0

容易做,如果你加載圖像時設置的回調:

function updateImage(domimage,src){ 
    var tempImg = new Image(); 
    tempImg.onload = function(){ 
     var ratio = this.width/this.height; 
     domimage.setAttribute("class", ratio < 1 ? "wide" : "tall"); 
    } 
    tempImg.src = src 
} 

用作:

 var ele = document.createElement("img"); 
     ele.setAttribute("id","img"+i); 
     ele.setAttribute("class","img_model"); 
     ele.setAttribute("style","width:100%;height:auto;"); 
     var imagesrc = "http://xxx.jpg"; 
     ele.setAttribute("src",imagesrc); 
     document.getElementById("a"+i).appendChild(ele); 
     updateImage(ele,imagesrc) 

未經測試。我忘記了如何使用香草選擇器。使用jquery。真的更簡單,更乾淨