2016-05-11 200 views
0

我試圖把一張圖片放在我的背景上,我的想法是圖像填滿了整個窗口,不管它是多大。填充窗口背景

我使用HTML,CSS和腳本如下:

// Funcao adaptImage() 
 
// Parametros: targetimg 
 
function adaptImage(targetimg) { 
 
    var wheight = $(window).height(); 
 
    var wwidth = $(window).width(); 
 

 

 
    targetimg.removeAttr("width") 
 
    .removeAttr("height") 
 
    .css({ width: "", height: "" }); 
 

 
    var imgwidth = targetimg.width(); 
 
    var imgheight = targetimg.height(); 
 

 
    var destwidth = wwidth; 
 
    var destheight = wheight; 
 

 

 
    if(imgheight < wheight) { 
 

 

 
    destwidth = (imgwidth * wheight)/imgheight; 
 

 
    $('#fundo img').height(destheight); 
 
    $('#fundo img').width(destwidth); 
 
    } 
 

 

 

 

 
    destheight = $('#fundo img').height(); 
 
    var posy = (destheight/2 - wheight/2); 
 
    var posx = (destwidth/2 - wwidth/2); 
 

 

 
    if(posy > 0) { 
 
    posy *= -1; 
 
    } 
 
    if(posx > 0) { 
 
    posx *= -1; 
 
    } 
 

 

 
    $('#fundo').css({'top': posy + 'px', 'left': posx + 'px'}); 
 
} 
 

 

 
$(window).resize(function() { 
 
    adaptImage($('#fundo img')); 
 
}); 
 

 

 
$(window).load(function() { 
 
    $(window).resize(); 
 
});
#fundo-externo { 
 
    overflow: hidden; 
 
    width: 100%; 
 
    height: 100%; 
 
    position: relative; 
 
} 
 

 
#fundo { 
 
    position: fixed; 
 
    width: 100%; 
 
    height: 100%; 
 
} 
 

 
#fundo img { 
 
    width: 100%; 
 
    position: absolute; 
 
} 
 

 
#site { 
 
    position: absolute; 
 
    top: 40px; 
 
    left: 50%; 
 
    width: 560px; 
 
    padding: 20px; 
 
    margin-left: -300px; 
 
    background: #FFF; 
 
    background: rgba(255,255,255,0.8); 
 
}
<body> 
 
    <div id="fundo-externo"> 
 
    <div id="fundo"> 
 
     <img src="http://placehold.it/1920x1080" alt="" /> 
 
    </div> 
 
    </div> 
 
</body>

我的問題是在一些設備中,背景沒有完全填滿,它下面會出現一個白名單。

任何想法,將幫助非常感謝

+0

如果您創建一個顯示問題的小提琴(https://jsfiddle.net/),那就太好了。 –

回答

2

使用此設置爲背景圖片

.for_background_img { 
    background-size: cover; 
    background-size: 100%; 
    background-repeat: no-repeat; 
    height: 100%; 
} 
0

不使用<img>標籤,但使用圖片作爲背景圖片爲您的身體:

body { 
    background: url('http://placehold.it/1920x1080') no-repeat; 
    background-position: fixed; 
    background-size:cover; 
}