CSS背景重复:no-repeat;仍在重复。

3

I have...

    html, body {
    background-size: contain;
    background-repeat: no-repeat;
    }

在我的CSS和HTML中,我有以下内容:
<html>
<head> 
<title>Wut</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div id="page">
    </div>
   <script type="text/javascript">
        var imgCount = 3;
        var dir = 'img/';
        var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
        var images = new Array();
            images[1] = "1.png",
            images[2] = "2.png",
            images[3] = "3.png",
         document.body.style.background = "url(" + dir + images[randomCount] + ")";
    </script>
</body>

出于某种原因,由JS随机选择的背景图滚动了,而我不希望/需要它滚动。另外顺便说一下:我曾经成功让它停止滚动,但当我添加background-color后,背景图的一半被覆盖了,你无法看到背景图本身。
感谢您的帮助。
4个回答

5
发生这种情况的原因是因为background是一个复合属性,包括background-colorbackground-imagebackground-repeatbackground-positionbackground-attachment。这意味着当你仅设置background而没有指定background-repeat时,你只是覆盖了先前定义的规则,它会回退到默认值repeat。要修复它,你应该明确提供它:
document.body.style.background = "url(" + dir + images[randomCount] + ") no-repeat";

或者改为设置background-image
document.body.style.backgroundImage = "url(" + dir + images[randomCount] + ")";

+1 是为了解释属性被覆盖的原因。 - undefined

1
添加这行代码。
document.body.style.backgroundRepeat="no-repeat";

或者用另一种方式替换此行。
document.body.style.background = "url(" + dir + images[randomCount] + ") no-repeat";

HTML

<html>
  <head> 
   <title>Wut</title>
   <link href="style.css" rel="stylesheet" type="text/css">
  </head>

<body>
    <div id="page">
    </div>
   <script type="text/javascript">
        var imgCount = 3;
        var dir = 'img/';
        var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
        var images = new Array();
            images[1] = "1.png",
            images[2] = "2.png",
            images[3] = "3.png",
         document.body.style.background = "url(" + dir + images[randomCount] + ")";
         document.body.style.backgroundRepeat="no-repeat";
    </script>
</body>

CSS无需定义


0

因为你使用 document.body.style.background 覆盖了整个背景样式,包括重复属性。

请改用 document.body.style.backgroundImage

JSFiddle


0
原因是你设置了整个背景属性,这会覆盖任何具体的设置,比如背景重复(background-repeat)。尝试使用以下代码:
document.body.style.background-image = "url(" + dir + images[randomCount] + ")"

而不是你所拥有的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接