简体   繁体   English

如何在javascript中更改主体背景图片大小?

[英]how do i change body background image size in javascript?

I'm trying to fit my 'body' background image to the browsers document size. 我正在尝试将我的“身体”背景图片调整为浏览器的文档大小。 This code here doesn't change anything in browser when i run it... i see the image but it is repeated twice and the size isn't changing. 当我运行它时,这里的代码不会改变浏览器中的任何内容……我看到了图像,但是重复了两次,并且大小没有变化。 when debugging i see that the width and height variables are correct but nothing actually happens.... any ideas? 调试时,我看到width和height变量正确,但实际上什么也没发生。

 $(function() { // onload...do var width = $(document).width(); var height = $(document).height(); $('body').css.backgroundSize = "" + width + "px " + height + "px"; }); 
 body{ background: url(../images/MainMenuScreen.jpg); } 

Try this: 尝试这个:

#yourdiv /* with CSS 3 */
{  
 background: url(../images/MainMenuScreen.jpg) no-repeat;
 background-size: 100%;
}

You can use the background-size:cover property. 您可以使用background-size:cover属性。 Using "background-size:cover" property will give you the following advantages: 1. It Fills entire page with image, no white space 2. Scales image as needed 3. Retains image proportions (aspect ratio) 4. Image is centered on page 5. Does not cause scrollbars 6. As cross-browser compatible as possible 使用“ background-size:cover”属性将为您提供以下优势:1.它用图像填充整个页面,没有空白2.根据需要缩放图像3.保留图像比例(长宽比)4.图像居中5.不会引起滚动条。6.尽可能兼容跨浏览器

Here is the css (if you want it to apply to the entire page) : 这是CSS(如果您希望将其应用于整个页面):

html { 
background: url(../images/MainMenuScreen.jpg) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM