小提琴示例:http://jsfiddle.net/wmnWc/5/
调整视口窗口的大小以查看我正在尝试实现的目标。
正如您在我的代码中所看到的,我已经设置了容器高度,其最小高度值为表单容器的外部高度。这是因为我希望能够滚动到表单的自然高度,仍然可以看到背景图像。
我还需要图像始终保持其自然比例。正如你所看到的,这就是我试图做的事情。
样本图片尺寸:
代码:
$(window).bind("resize.browsersize", function () {
var viewportHeight = $(window).height(),
viewportWidth = $(window).width(),
loginHeight = $('#login').outerHeight(),
containerHeight = $('.background-photo').height(),
containerWidth = $('.background-photo').width(),
ratioHeight = 1,
ratioWidth = 1.497;
$(".background-photo").css({
'width': viewportWidth + 'px',
'height': viewportHeight + 'px',
'min-height': loginHeight + 'px'
});
if (containerHeight > containerWidth) {
$(".background-photo img").css({
'height': containerHeight + 'px',
'width': containerHeight * ratioWidth + 'px',
'max-width': containerHeight * ratioWidth + 'px'
});
} else if (containerWidth > containerHeight) {
$(".background-photo img").css({
'width': containerWidth + 'px',
'height': 'auto',
'max-width': containerWidth + 'px'
});
}
}).trigger("resize.browsersize");
提前致谢。
约什
答案 0 :(得分:1)
有没有理由不能使用background-size: cover
?
html {
background: url('http://www.motocomdigital.co.uk/login-background.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
请参阅:http://jsfiddle.net/wmnWc/7/
适用于:
Safari 3+
Chrome Whatever+
IE 9+
Opera 10+ (Opera 9.5 supported background-size but not the keywords)
Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)
答案 1 :(得分:1)
为什么不保持简单?
.background-photo { position:absolute; top:0; left:0; width:100%; height:100%; z-index:-1; overflow:hidden; }
img { max-width:100%; /*min-width:600px;*/ }
$(document).ready(function(){
var imgRatio;
$("img").load(function(){
var $i = $(this);
imgRatio = $i.width()/$i.height();
var $w = $(window);
$w.on("resize",function(){
$i.css("min-width",$w.height() * imgRatio);
}).resize();
});
});
答案 2 :(得分:0)
此代码段可以帮助您: 我设置了一个最小高度,它垂直填充浏览器窗口,并设置100%宽度,水平填充它。然后设置图像宽度的最小宽度,使图像不会小于它的大小。这更容易,没有js。
.background-photo img {
min-height: 100%;
min-width: xxxxpx;/* image width */
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}