【问题标题】:Javascript function on the first load page第一个加载页面上的 Javascript 函数
【发布时间】:2020-10-05 07:38:28
【问题描述】:

我正在寻找一个粘性页脚,我发现了这个 https://gist.github.com/robertvunabandi/b66dc9872f51c93af796094e08155731

这非常有用,但问题是当我刷新页面时,页脚首先出现在顶部,1 秒后它出现在底部的正确位置,有没有办法避免这种情况?我的意思是当我刷新页面时,页脚应该出现在底部?


window.addEventListener("load", activateStickyFooter);
function activateStickyFooter() {
  adjustFooterCssTopToSticky(); 
  window.addEventListener("resize", adjustFooterCssTopToSticky);
}

function adjustFooterCssTopToSticky() {
  const footer = document.querySelector("#footer");
  const bounding_box = footer.getBoundingClientRect();
  const footer_height = bounding_box.height;
  const window_height = window.innerHeight;
  const above_footer_height = bounding_box.top - getCssTopAttribute(footer);
  if (above_footer_height + footer_height <= window_height) {
    const new_footer_top = window_height - (above_footer_height + footer_height);
    footer.style.top = new_footer_top + "px";
  } else if (above_footer_height + footer_height > window_height) {
    footer.style.top = null;
  }
}

function getCssTopAttribute(htmlElement) {
  const top_string = htmlElement.style.top;
  if (top_string === null || top_string.length === 0) {
    return 0;
  }
  const extracted_top_pixels = top_string.substring(0, top_string.length - 2);
  return parseFloat(extracted_top_pixels);
}

【问题讨论】:

  • 使用CSS设置位置到底部?无论如何,这很可能都可以通过 CSS 完成,但如果你想这样做,那也没关系。

标签: javascript html footer


【解决方案1】:

我想在页面加载事件中使用 JS 操作 DOM 元素不是一个好主意。最好使用 CSS 来解决问题:

How to make a sticky footer using CSS?

【讨论】:

    【解决方案2】:

    如果你用 CSS 做,应该不会有这个问题,而且代码行数很少,我做了一个快速模型作为示例。


    HTML:

    <header>Header</header>
    
    <main>Main</main>
    
    <footer>Footer</footer>
    


    CSS:

     header {
       background-color:blanchedalmond;
       height: 10vh;
       min-height: 60px;
    
      }
    
    
     main {
        background-color:beige;
        height: 70vh;
        min-height: 800px;
      }
    
      footer {
        background-color:blanchedalmond;
        height: 20vh;
        min-height: 200px;
        position: -webkit-sticky;
        position: sticky;
        bottom: 0;
      }
    

    【讨论】:

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