调整div背景的大小

时间:2015-04-06 14:55:13

标签: javascript jquery html css frontend

一开始我想为我的英语道歉..
但削减追逐 - 我做我的第一个网站,我有div背景的问题。我想在调整浏览器窗口大小时更改div的背景分辨率,如http://kamilnizinski.plhttp://rumblelabs.com - 正如您可以看到在调整窗口大小时背景完全改变分辨率。在我的CSS文件中我有

.background { 
height: 100%; 
background-image: url('img/background.png'); 
background-repeat: no-repeat; 
background-attachment: fixed; 
background-size: cover; 
background-position: center; } 

所以我在没有调整大小的情况下获得图像的一部分。所以我的问题是 - 我怎么能得到这种效果?我必须在CSS中改变一些东西,或者我必须使用javascript / jQuery?
提前感谢您的回答。

2 个答案:

答案 0 :(得分:1)

简单示例:

http://jsfiddle.net/xkaL2rho/

HTML:

<div class='background' />

的CSS:

.background{
    background-image: url(http://blendr.io/wp-content/uploads/2014/05/Polygon-Background-2.jpg);
    background-size: cover;
    height:100%;
}
html, body{
    height:100%;
    width:100%;
}

另一种方法是使用javascript:

http://jsfiddle.net/xkaL2rho/1/

的CSS:

.background{
    background-image: url(http://blendr.io/wp-content/uploads/2014/05/Polygon-Background-2.jpg);
    background-size:cover;
}
html, body{
    height:100%;
    width:100%;
}

JS:

$(window).resize(function(){
    doResize()    
});

function doResize(){
    var width = $(window).width();
    var height = $(window).height();
    $('.background').css({'width':width+'px',height: height+'px'})
}

doResize();

答案 1 :(得分:0)

我不完全确定你提到的网站是如何做到这一点的,但我建议在你的css中使用@media标签

媒体标签允许您根据屏幕尺寸定义css规则。

查看此Google基础知识,了解@media和屏幕尺寸。 Use CSS media queries for responsiveness

我建议使用它的原因是你可以控制的不仅仅是图像,而是按屏幕尺寸控制文字或按钮。

相关问题