2015-12-27 29 views
2

我试图将图像追加到具有指定高度和宽度的元素。图像本身可能比这个高度和宽度更大或更小,我想调整图像以适合尺寸,而不是重复或仅显示图像的一部分。使用javascript添加适合设置尺寸的图像

的Javascript:

我得到了图像的URL以及它的高度和宽度,然后我试图创建的元素,在这里设置其属性。

 var listingEntry = document.createElement("img"); 
    listingEntry.setAttribute("height", height); 
    listingEntry.setAttribute("width", width); 
    listingEntry.className = "classTitle"; 
    listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")"; 

然后,我通过标识得到了来自DOM元素,并追加它:

 var gridArticle = document.getElementById("gridArticle"); 
    gridArticle.appendChild(listingEntry); 

我的CSS:

article .tile { 

display: inline-block; 
float: left; 
box-sizing: border-box; 

font-size: 3em; 
font-weight: 700; 

padding: 0 6px; 
color: #fff; 
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; 

} 

article img { 

} 

我想:

article img { 
    max-height: 100% 
    max-width: 100% 
} 

但然后图像停止显示在一起。

回答

2

我会以两种不同的方式接近这一点:

1)创建一个div和设置背景图片:

var listingEntry = document.createElement("div"); 
listingEntry.setAttribute("height", height); 
listingEntry.setAttribute("width", width); 
listingEntry.className = "classTitle"; 
listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")"; 

或2)创建一个img,并设置一个指向URL一个src:

var listingEntry = document.createElement("img"); 
listingEntry.setAttribute("height", height); 
listingEntry.setAttribute("width", width); 
listingEntry.className = "classTitle"; 
listingEntry.src = imageSourceUrl; 

注:我会去的第二种方法。同时尽量避免将背景图像设置为img元素,因为元素的内容倾向于掩盖背景。

+0

我目前使用的方式编号1,它工作正常。你知道我必须调整哪些属性,以便图像可以缩放以适合我指定的任何尺寸,以便它不重复图像或仅显示一部分? – Pipeline

+0

请尝试以下操作: overflow:hidden; background-size:cover; background-position:center; – el3ati2

2

你需要设置你的图像来源:

var listingEntry = document.createElement("img"); 
listingEntry.setAttribute("height", height); 
listingEntry.setAttribute("width", width); 
listingEntry.className = "classTitle"; 

listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")";

listingEntry.src = imageSourceUrl;