2016-11-11 30 views
0

我需要一個腳本(JavaScript的)以限定主體背景的onload, 因爲第一我有一個腳本以查看其是網頁的widht和高度。然後,它給了我兩個變量(「W」和「H」)。 我想要的背景具有寬度= W和高度= H。 所以也許,最好的解決辦法是運行一些腳本,得到的寬度和頁面的高度後,把對身體的背景。腳本來定義負載的背景下,以寬度/高度可變

<script> 
function fundo() { 
var w = window.innerWidth 
|| document.documentElement.clientWidth 
|| document.body.clientWidth; 

var h = window.innerHeight 
|| document.documentElement.clientHeight 
|| document.body.clientHeight; 

} 

</script> 
</head> 
<body onload="fundo()" style="background: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRiu8PAY4rJ4WNg2MqwpMfBQ5w3jAXxu5JMYhgImhog9quU-ikZWq8AgQ'; width: "+ w +" height: "+ h +";" > 
</body> 
+0

和W帽子到底是你的問題?你嘗試過window.onload,它不適合你嗎? –

+0

增加了我的代碼的第一篇文章@AlexeySoshin –

+0

無法理解你的問題。你有工作代碼在哪裏測試? –

回答

1

,你應該那樣做:

var url = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRiu8PAY4rJ4WNg2MqwpMfBQ5w3jAXxu5JMYhgImhog9quU-ikZWq8AgQ"; 
 
function fundo() { 
 
    var w = window.innerWidth 
 
      || document.documentElement.clientWidth 
 
      || document.body.clientWidth; 
 

 
    var h = window.innerHeight 
 
      || document.documentElement.clientHeight 
 
      || document.body.clientHeight; 
 

 
    document.body.style.background = "url('" + url + "')"; 
 
    document.body.style.backgroundSize = w + "px " + h + "px"; 
 
}
<body onload = "fundo()"></body>

+0

是的,我真的沒有理由不這樣做在CSS。在CSS中更容易,我已經做到了。但由於我不熟悉javascript,我不得不問。謝謝! –

0

無論如何,身體是完整的高度和寬度。你應該可以用純CSS完成所有這些。您可以使用背景大小,以確保它填補可用面積:

body { 
    width: 100%; /* set just in case */ 
    height: 100%; /* set just in case */ 
    background-image: url(pathtoimage); 
    background-repeat: no-repeat; 
    background-position: center center; 
    background-size: cover; 
} 

這將拉伸圖像填充它:如果你有一些特殊原因不能做到這一點在CSS

body { 
    width: 100%; /* set just in case */ 
    height: 100%; /* set just in case */ 
    background-image: url(pathtoimage); 
    background-repeat: no-repeat; 
    background-position: center center; 
    background-size: 100% 100%; 
}