javascript - CSS 图像没有覆盖整个屏幕

标签 javascript jquery html css

我希望我的 css 图像覆盖整个屏幕,我从 JS 数组中随机选择一个图像。它显示图像,但未显示完美的整页背景图像。

ma​​in.html

<html>
  <head>
    <link rel="stylesheet" href="main.css">
  </head>
  <body>

<button id = "button1">Click</button>


    <script src = "main.js"></script>
  </body>
</html>

ma​​in.js

    document.getElementById("button1").addEventListener("click", function(){
      showImage();
    });
    ...
    function showImage(){
    document.write('<img class = "bg" src="'+theImages[whichImage]+'">');
    }

ma​​in.css

img.bg {
  /* Set rules to fill background */
  min-height: 100%; 
  min-width: 1024px;

  /* Set up proportionate scaling */
  width: 100%;
  height: auto;

  /* Set up positioning */
  position: fixed;
  top: 0;
  left: 0;
}

@media screen and (max-width: 1024px) { /* Specific to this particular image */
  img.bg {
    left: 50%;
    margin-left: -512px;   /* 50% */
  }
}

最佳答案

那是什么CSS?我也不建议使用 vw/vh。

你最好使用标准的背景尺寸和位置,比如

/*background-image: url(../images/background.png);*/ optional
background-size: cover;
background-repeat: no-repeat;
background-position: left top;

你可以随时添加

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;

为了全面的跨浏览器兼容性

关于javascript - CSS 图像没有覆盖整个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217968/

相关文章:

javascript - Yii2-如何在 javascript 中隐藏下拉列表中的值

cshtml @Url.Action(Action, Controller) 的 JavaScript 类比

javascript - js或php函数前的下划线是什么意思?

javascript - IE 需要双击自定义按钮

html - 当变量为负时如何更改背景颜色?

html - 使用位置 : relative 将文本和图像定位为水平居中

javascript - 如何检查React中的prop函数是否被点击

javascript - 从键中提取公共(public)值并制作多维数组

javascript - 替换字符串的最后一个字符

javascript - 将事件类添加到菜单