gpt4 book ai didi

javascript - CSS整页背景缩放问题

转载 作者:行者123 更新时间:2023-11-28 14:56:44 25 4
gpt4 key购买 nike

如何制作整页背景图片而不拉伸(stretch)它 (something like this)?

<html>
<style>
html, body {height:100%;}
#background {
min-height:100%;
min-width:1024px;
width:100%;
height:auto;
position:fixed;
top:0;
left:0;
z-index:-1;
}
@media screen and (max-width: 1024px){ #background{left:50%;margin-left:-512px;}}
</style>

</head>
<body>
<img id="background" src="http://www.iwallpapers.in/bulkupload/C/Mountains/Mountains%2040.jpg" alt="" />
</body>
</html>

Pastebin here

编辑:

上面的代码可能会更好地说明我的目标。当您将窗口大小调整为 400px 时,您会得到 empty space under the image .我希望图像填满整个窗口并保持其纵横比。

<!DOCTYPE html>
<html lang="en">
<head><head>
<title></title>
<style>
*{margin:0; padding:0;}
#wrap{
width:100%;
height:auto;
margin:0 auto;
}
#bg{ width:100%}
</style>
</head>

<body>
<div id="wrap">
<img src="http://www.bmwgallery.co.uk/bmw-motorcycles/bmw-s1000rr-superbike-motorcycle-large.jpg" id="bg" />
</div>
</div>

</body>
</html>

最佳答案

如果你想让背景像那样动态变化,我认为你必须使用 JavaScript。如果您不希望图像变形,则必须使用一维并保持纵横比,例如:

<!doctype HTML>
<html>
<head>
<style type = "text/css">
#backgroundDiv{position:absolute;}
</style>
<script type="text/javascript" language="JavaScript" src="jquery-1.4.2.min.js"></script>
<script type ="text/javascript" language="JavaScript">
function resizeImg(){
var h = parseInt($(document).height()) - 50;
var imgh = $("#bg-image").height();
var imgw = $("#bg-image").width();
$("#bg-image").height(h);
$("#bg-image").width(Math.floor(imgw*(h/imgh)));
}
$(document).ready(function(){
resizeImg();
$(window).resize(function(){
resizeImg();
});
});
</script>
</head>
<body>
<div style = "height:100%;width:100%;" id = "backgroundDiv"><img src = "slider-image.jpg" id = "bg-image"></div>
</body>
</html>

希望对您有所帮助! (如果你想让它在背景中,请尝试调整图像的 z-index )

关于javascript - CSS整页背景缩放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3526761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com