我得到了一张1920x1080的背景图像。我想调整此图像的大小并居中以填充屏幕,并始终居中。我使用了两种不同的方法:
1:
.background{
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
2:
.background{
max-width: 100%;
max-height: 100%;
}
两者都在我的台式电脑上工作,分辨率为1280x1024(是的,它们仍然存在)。但当我在分辨率为1920x10180的手机上纵向查看此页面时,图像并没有填满整个屏幕。
桌面
手机
正如你所看到的,图像并没有像我手机上那样充满屏幕。当cover
大于图像本身时,它不会填充屏幕吗?如果是,我该如何解决?
编辑:完整风格的.background
:
.background{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-position:center center;
filter: blur(3px);
-webkit-filter: blur(3px);
-moz-filter: blur(3px);
-o-filter: blur(3px);
-ms-filter: blur(3px);
z-index: 0;
}
第2版:我生成一个随机图像作为<div class="background></div>
:的background
<script type="text/javascript">
var NUMBER_OF_IMAGES = 5;
var rand;
var setImage = false;
function randomIntFromInterval(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
//Generate random image
if(!setImage){
rand = randomIntFromInterval(1, NUMBER_OF_IMAGES);
document.getElementById('background').style.background = 'url(img/' + rand + '.jpg) no-repeat center center fixed';
}
</script>
使用背景大小:cover,背景图像会填充整个区域。你的手机屏幕截图看起来真的像你应用了背景大小:包含。
在JS中,您使用background
简写属性,它不仅设置URL/reply/position,而且用默认属性覆盖您最初在CSS中定义的background-size
属性。
在动态更新后台后,尝试在JS中添加一行以"重置"background-size
:
document.getElementById('background').style.background = 'url(img/1.jpg) no-repeat center center fixed';
document.getElementById('background').style.backgroundSize = 'cover';
同样在您的代码中,您使用getElementById
,但在CSS 中有一个类选择器
Fiddle:http://jsfiddle.net/2vnasec5/