固定的背景图片和绝对定位的包装器

时间:2018-07-22 17:01:45

标签: html css

我仅在Google Chrome上遇到问题。基本的CSS样式在两种浏览器上的行为不同,我不明白为什么。

这是Firefox上的行为,这是所需的结果:

enter image description here

这是Chrome上的行为,这不好,因为图像在滚动时会下降:

enter image description here

您可以在此JSFiddle上重现它:https://jsfiddle.net/zcugdayv/26/

为了解决该问题,我尝试将代码减少到最少:

.app {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

.parallax-wrapper {
  height: 100vh;
  background: url('http://m0.libe.com/blogs/cache/3e/9f/3e9f3c94db337827f6d1d0a859a433f4.jpg') fixed center;
  background-size: cover;
}

.normal-wrapper {
  height: 600px;
  background: green;
}
<div class="app">
  <div class="parallax-wrapper"></div>
  <div class="normal-wrapper"></div>
</div>

我知道,如果我不在position: absolute;类上使用app,它将再次起作用,但是出于不同的原因,我需要这样做。

您是否认为这是Google Chrome本身的错误,是否会在以后的版本中修复,或者是由于特定原因Google Chrome本身实现的新功能?

如果Google Chrome浏览器的行为正常,为什么图像会消失?我所看到的是什么数学?

2 个答案:

答案 0 :(得分:1)

我不确定为什么会在Chrome中发生这种情况,但我为您提供了一种解决方法。在每个规则中添加以下内容,它应该可以正常工作。

.parallax-wrapper {
    position: fixed;
    top: 0;
    width: 100%;
}
.normal-wrapper {
    margin-top: 100vh;
    z-index: 1;
    position: relative;

}

答案 1 :(得分:1)

更新的代码段:

看看这段代码,我认为这可以解决您的问题:

public class AsyncCache<TKey, TValue>
{
    private readonly Func<TKey, Task<TValue>> _valueFactory;
    private readonly ConcurrentDictionary<TKey, Lazy<Task<TValue>>> _map;

    public AsyncCache(Func<TKey, Task<TValue>> valueFactory)
    {
        if (valueFactory == null) throw new ArgumentNullException("loader");
        _valueFactory = valueFactory;
        _map = new ConcurrentDictionary<TKey, Lazy<Task<TValue>>>();
    }

    public Task<TValue> this[TKey key]
    {
        get
        {
            if (key == null) throw new ArgumentNullException("key");
            return _map.GetOrAdd(key, toAdd => 
                new Lazy<Task<TValue>>(() => _valueFactory(toAdd))).Value;
        }
    }
}
* {
  margin: 0;
  padding: 0;
}

body {
  position: relative;
  width: 100%;
}

#app {
  position: absolute;
  width: inherit;
}

div div {
  width: 100%;
  height: 100vh;
  background: red;
}

div.parallax-wrapper {
  background-image: url('http://m0.libe.com/blogs/cache/3e/9f/3e9f3c94db337827f6d1d0a859a433f4.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

您还可以在这里查看结果: https://jsbin.com/mebecirino/edit?html,css,output

相关问题