简体   繁体   English

媒体查询div背景图片变化怪异

[英]Media query div background image change weirdness

I have div with a simple background image. 我有一个简单的背景图像的div。 I'd need to change the image and how it's being displayed for responsiveness however I see some weird behavior happening when I resize the browser, the cover image either doesn't show at first or shows in pieces, when I resize a second time even if it's just one pixel change it starts showing. 我需要更改图像及其显示方式以提高响应速度,但是,当我调整浏览器大小时,我看到一些奇怪的现象发生,当我第二次调整大小时,封面图像要么先不显示要么成片显示如果只是一个像素变化,它将开始显示。 Refreshing the browser in any size works just fine. 刷新任何大小的浏览器都可以。 Any idea why this is happening and how to fix it? 知道为什么会这样以及如何解决吗?

.mydiv {
  background: url(../img/background1.jpg) no-repeat;
  background-position: center center;
}

@media (max-width:992px) {
  .mydiv {
    background: url(../img/background2.jpg) no-repeat;
    background-position: center center;
    background-attachment: fixed;
    background-size: cover;
  }
}

Edit: I've noticed that when I inspect element and touch .mydiv the weirdness goes away, so I wonder if there's a way to get Javascript or JQuery to refresh my element or something like that. 编辑:我注意到,当我检查元素并触摸.mydiv时,怪异感消失了,所以我想知道是否有办法让Javascript或JQuery刷新我的元素或类似的东西。

I see a couple of things right off the bat: 我马上看到了几件事:

  1. Add a space between @media and (max-width:992px) @media(max-width:992px)之间添加一个空格
  2. Are you using a mydiv element, or is that supposed to be a class or ID name? 您正在使用mydiv元素,还是应该使用类或ID名称? If it's a class or id, then you need to refer to it as either .mydiv (class) or #mydiv (ID) in your CSS. 如果是类或ID,则需要在CSS #mydiv其称为.mydiv (类)或#mydiv (ID)。

Here's a working jsfiddle. 这是一个工作的jsfiddle。

Rewrite the media query correctly, adding a space and if you wish for more clarity use @media which by itself it's impliciting defining @media all, but you can also use a parameter but then you need to add 正确地重写媒体查询,添加一个空格,如果您希望更清楚一点,请使用@media,它本身就是隐式定义@media all,但是您也可以使用参数,但是您需要添加

I'm using 768px just for testing purposes in this case. 在这种情况下,我仅将768px用于测试目的。 Update it with the value you need. 用您需要的值更新它。

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

      }

DEMO CODE 演示代码

html,body{
    height:100%;
}
.mydiv {
    width:100%;
    height:100%;
  background: url('http://placehold.it/1000x1000/FFF/000') no-repeat;
  background-size:cover;
  background-position: center center;
}

@media (max-width: 768px) {
  .mydiv {
    background: url(http://placehold.it/1000x1000/) no-repeat;
    background-position: center center;
  }
}

Check this demo: 查看此演示:

https://jsfiddle.net/a_incarnati/v575uvyb/5/ https://jsfiddle.net/a_incarnati/v575uvyb/5/

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

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