代码之家  ›  专栏  ›  技术社区  ›  dukedevil294

短页上的粘性页脚强制下移

  •  0
  • dukedevil294  · 技术社区  · 7 年前

    下面是一个非常简单的例子,说明了我在使用粘性页脚时遇到的问题。当页面内容没有填满视口时,页脚被视为静态定位的元素。我意识到这在技术上是 position: sticky 但我想知道是否有一种方法可以从本质上迫使它永远 position: fixed 在这种情况下。我不想从文档流中删除元素,这就是为什么我不只是将其更改为永久固定。此外,页面可以具有可变高度(基于内容),因此如果页面比视口长,则需要粘性行为。

    html { height: 100%; }
    body { min-height: 100%; }
    .content {
        width: 100%;
        max-width: 1140px;
        padding-right: 15px;
        padding-left: 15px;
        margin-right: auto;
        margin-left: auto;
    }
    .footer {
        position: sticky;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1030;
    }
    <html>
      <body>
        <div class="content">
          Here is some sample content
        </div>
        <div class="footer">
          This is the sticky footer
        </div>
      </body>
    </html>
    1 回复  |  直到 7 年前
        1
  •  0
  •   Noah B    7 年前

    此代码将根据相对于窗口高度的文档高度更改页脚样式。

    function init() {
        if (window.innerHeight < document.body.clientHeight) {
            document.querySelector(".footer").style.position = "sticky";
        }
        else {
            document.querySelector(".footer").style.position = "fixed";
        }
    
    window.onload = init;