javascript - 如何在手机中更改背景图像?

标签 javascript html css media-queries

我正在开发一个带有背景图片的简单 html 页面。在桌面上,背景显示完美,但我想在移动设备上更改背景图片。

html和css如下:

HTML

<div class="pc-img" ></div>
<div class="mobile-img" ></div>

CSS

body
{
    margin:0px;
    padding: 0px;
}

.pc-img {
     min-height: 95% !important;
    height: 100%;
    width: 100%;
    background-image: url('http://www.laminaresearchcenter.com/images/comingsoon.png');
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    text-align: center;
    color: white;
}
}

.mobile-img
{
    display: none;
}

@media only screen and (max-width: 384px) {

.mobile-img
    {
         background: url('http://www.outbarga.in/images/comingsoon.jpg');

       visibility: visible;
}

.pc-img
{
    visibility: hidden;
}
}

最佳答案

您不需要 2 个类和 2 个 div 来执行此操作。 您可以为一个 div 设置 @media 查询,并更改他的属性。

CSS:

.pc-img {
  width: 100%;
  height: 400px;
  background: #000;
}

@media screen and (min-width: 100px) and (max-width: 480px) {
  .pc-img {
    background: purple;
  }
}
@media screen and (min-width: 480px) and (max-width: 768px) {
  .pc-img {
    background: yellow;
  }
}

看这个演示: Demo 1

顺便说一句,如果您想要两个 div,请执行以下操作: Demo 2

.pc-img {
  width: 100%;
  height: 400px;
  background: #000;
}
.device-img {
  background: steelblue;
  width: 100%;
  height: 400px;
}
@media screen and (min-width: 100px) and (max-width: 480px) {
  .device-img {
    display: block;
  }
  .pc-img {
    display: none;
  }
}
@media screen and (min-width: 480px) and (max-width: 768px) {
  .device-img {
    display: block;
  }
  .pc-img {
    display: none;
  }
}

关于javascript - 如何在手机中更改背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053765/

相关文章:

javascript - Chart JS — 条件水平行背景色

jquery - 在 javascript 中,我如何知道函数需要什么类型的参数

javascript - 如何实现点从a到b的移动过渡

javascript - HTML5 Canvas 坐标给出了奇怪的 Angular

css - ie6 背景图像 png AlphaImageLoader 使用 mootools 1.11 加载后出现问题

javascript - 动态下拉框验证

javascript - 如何更改 span 的文本并显示 div?

html - clientHeight 在 IE 中不起作用

html img 百分比在 ipad 中看起来很尴尬

html - 如何保持选中的列表项