【问题标题】:iOS moves background image when positioning fixediOS在定位固定时移动背景图像
【发布时间】:2014-06-11 08:48:27
【问题描述】:

我希望我的背景图片保持在同一位置。所以我利用了

background-attachment:fixed;

当我发现 iOS 显然不支持这个属性时,我决定在 DOM 中放置一个固定的背景 div。这实际上效果很好:

#background {
    top:0;
    left:0;
    width:100%;
    height:100%;
    position:fixed;
    background-position:50% 0%;
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-image:url("images/mark-bg.png");
}

乍一看,这在 iOS 中也很有效。但后来我意识到,如果不修复,Safari 会将 DIV 向上滚动到它本来可以滚动的位置。

现在我问自己»这到底是什么......?!«我的意思是......为什么iOS会滚动一个明确告知不要这样做的元素?

有什么智能解决方案吗?

Here is a complete Demo

编辑

我刚刚发现,不是元素自己移动,而是背景图像移动......

【问题讨论】:

    标签: html ios css css-position fixed


    【解决方案1】:

    朱利安的回答对我很有帮助。

    它解决了部分问题,即通过将背景图像替换为固定位置 div 中的静态图像来防止滚动背景图像,避免 Safari 对“背景附件:固定”的错误解释。

    但是它给我留下了一个我无法在视口中居中的图像,因此图像的中心总是在视口的中心。

    这通常是 background-position: 50% 50% 和 background-size: cover,但当我们根本没有背景图像时则不然。

    所以我将 Julian 的内部 <img> 替换为具有类似设置的 <div>

    然后我将背景图像和属性添加到该 div,除了我遗漏的背景附件。

    这导致一个 div 占据了整个视口并固定在视口上,并且有一个子 div 完全填充它,并且该子 div 在位置 50%/50% 和大小处设置了一个静态背景图像封面。

    效果很好!

    我的内部div样式如下:

    #div_background > div
    {
        top: 0px;
        left: 0px;
        width: auto;
        height: auto;
        right: 0px;
        bottom: 0px;
        position: absolute;
        margin-left: auto;
        margin-right: auto;
        display: inline-block;
    
        background-image: url(/images/background.jpg);
        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;
    }
    

    与父div样式如下:

    #div_background
    {
        display: inline-block;
        position: fixed;
        top: 0px;
        left: 0px;
        height: 100%;
        width: 100%;
        right: 0%;
        bottom: 0%;
        z-index: -1;
        background-color: #A0B4C8;
    }
    

    HTML 很简单:

    <div id="div_background"><div></div></div>
    

    我认为这是一个 hacky 解决方案,但由于 Safari 的错误,这是一个必要的解决方案。

    一种简单的思考方式是,我们创建自己的固定背景并手动将带有背景图像的新 div 附加到该背景上,而不是使用固定的背景附件。

    谢谢,朱利安!

    【讨论】:

      【解决方案2】:

      我找到了一个不太理想的解决方案,但至少它有效。我不再在 CSS 中使用background-image,而是将img 标签放在背景 div 中并将其绝对定位:

      #background img {
          top:0;
          left:0;
          right:0;
          bottom:0;
          position:absolute;
      }
      

      Here is the fiddle

      不幸的是,“这是文本”段落不再可见。幸运的是,这只是为了背景......

      图像也不再居中,也没有正确调整大小:[

      编辑

      我添加了以下 CSS 来修复定位:

      #background img {
          margin-left:auto;
          margin-right:auto;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        相关资源
        最近更新 更多