用于定义负载背景的脚本,带有 width/height 变量

Script to define background on load, with width/height variable

我需要一个脚本(javascript)来定义body background onload, 因为首先我有一个脚本来查看页面的宽度和高度。然后,它给了我两个变量("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>

无论如何,body 是完整的高度和宽度。您应该能够使用纯 CSS 完成所有这些操作。您可以使用 background-size 来确保它填满可用区域:

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;
}

这将拉伸图像以填充它:

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%;
}

如果您有某些特定原因不在 CSS 中执行此操作,您应该这样做:

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>