2016-10-04 74 views
0

我想找到一種方法來獲得div中包含的背景圖像,如果它大於div(background-size:contains;)並且圖像小於div ,保持它,因爲它是不拉伸和模糊它(背景大小:自動;)CSS - 背景大小包含或正常

有沒有什麼辦法做到這一點?我沒有從長遠來看,圖像的控制,因爲它是一個WordPress網站(所以圖像也必然發生變化,而不會由程序員通過)

+0

如何變化的背景 - 大小與JS依賴於寬度? – Adam

+0

不要以爲你可以用JS獲取背景中使用的圖像的大小。如果可以的話,想知道如何。 – Fredy31

回答

0

window.onload = function() { 
 

 
    var imageSrc = document 
 
        .getElementsByClassName('foo') 
 
        .style 
 
         .backgroundImage 
 
         .replace(/url\((['"])?(.*?)\1\)/gi, '$2') 
 
         .split(',')[0]; 
 

 
    
 
    var divWidth = imageSrc.offsetWidth; 
 

 
    var image = new Image(); 
 
    image.src = imageSrc; 
 

 
    var width = image.width, 
 
     height = image.height; 
 

 
    alert('width =' + width + ', height = ' + height) 
 
    
 
    if (width > divWidth) { 
 
     
 
     imageSrc.style.backgroundSize = "contain"; 
 
     
 
    } 
 

 
}