background-size:封面; 属性

background-size: cover; property

每当背景图像发生变化时,我都需要它来覆盖 body。我正在使用 background-size: cover,但它似乎不起作用。

body {
   position: relative;
   margin-top: 60px;
   background-color: #000;
   font-family: 'Roboto Slab', serif;
   background: url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg); 
   background-repeat: no-repeat;
   background-position: center center;
   background-atachment: fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   transition: background 1s;

这是更改图像的 jQuery:

$("body").css("background", objects[newNum].img);

图像存储在数组中 (objects)。

代码笔:http://codepen.io/Chantun/pen/WxXaGy?editors=0010

背景封面是正确的工作。默认身高:自动。使用 min-height: 100vh 作为主体。并将 margin-top 更改为 padding-top.

body {
  min-height: 100vh;
  padding-top: 60px;
}

Codepen

您需要将 background 的用法更改为 background-image。因为和background-size冲突。

所以对于您的 CSS 它将是:

body {
   position: relative;
   margin-top: 60px;
   background-color: #000;
   font-family: 'Roboto Slab', serif;
   background-image: url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg); 
   background-repeat: no-repeat;
   background-position: center center;
   background-atachment: fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   transition: background 1s;

对于您的 JS,它应该是:

$("body").css("background-image", objects[newNum].img);

请注意!

background-attachment: fixedbackground-size: cover 玩得不是很好! :(

在此处更详细地解释它们如何以及为何发生冲突:

编辑:您的 background-attachment: fixed 也拼错了! :)

将您的 codepen 上的 background-attachment 更改为有两个 t 而不是一个 t 确实使它按照我认为您想要的方式工作。您还可以将您的后台规则组合成 shorthand,例如:

background: #000 url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg) center center / cover no-repeat;
background-attachment: fixed;