简体   繁体   English

Javascript - 添加顶部固定栏并将所有其他元素向下推

[英]Javascript - Adding a top fixed bar and push all the other elements down

I am trying to add top bar on a webpage which has 2 other elements that are top:0 and position:fixed.我正在尝试在一个网页上添加顶部栏,该网页有两个其他元素,它们是 top:0 和 position:fixed。 For example, think of a website with wp-admin bar and a menubar fixed on top.例如,考虑一个带有 wp-admin 栏和固定在顶部的菜单栏的网站。

I am creating a plugin & so I cannot modify the website's code, but can override styles.我正在创建一个插件 & 所以我不能修改网站的代码,但可以覆盖样式。

Here is my CSS:这是我的 CSS:

.bar-render-top
{
    top:0px;
    margin-top: 0px;
    position: fixed;
    z-index: 999999;
    width:100% !important;
}

I can see the bar but the others are hidden under it.我可以看到酒吧,但其他人隐藏在它下面。 What I would like for them is to 'move down'.我希望他们“向下移动”。 I could add custom css and find the elements' css and add margins, but since this is a plugin, it should work on any website.我可以添加自定义 css 并找到元素的 css 并添加边距,但由于这是一个插件,它应该适用于任何网站。 So I cannot add site-specific styles.所以我无法添加特定于站点的样式。

Ideally, this should behave like the mozbar chrome addon, which adds a topbar as an iframe.理想情况下,这应该像 mozbar chrome 插件一样,它将顶部栏添加为 iframe。

Is this possible?这可能吗? Any help would be highly appreciated.任何帮助将不胜感激。 Thank much.非常感谢。

 body { background-color: white; margin: 0; padding: 0; padding-top: 90px; } .fixed-bar { width: 100%; position: fixed; top: 0; height: 40px; line-height: 40px; text-align: center } .bar-1 { background-color: gold; } .bar-2 { background-color: pink; margin-top: 40px; } .my-bar { background-color: blue; height: 40px; line-height: 40px; text-align: center; color: white; }
 <div class="fixed-bar bar-1"> fixed bar one </div> <div class="fixed-bar bar-2"> fixed bar two </div> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sodales libero enim, sed convallis leo ornare eget. Nullam condimentum, diam ullamcorper sollicitudin fringilla, eros nisi placerat tellus, at volutpat velit felis eu ipsum. Suspendisse sed nisl a orci dapibus euismod et eget odio. Maecenas elementum erat elit, et efficitur ex feugiat ac. Nam convallis blandit nisl, finibus pretium tortor vehicula at. Sed ultricies finibus consectetur. Nulla nec diam a velit pellentesque consequat ut a lorem. Fusce eget massa lorem. In egestas risus non nisi condimentum facilisis. Quisque vulputate est ut odio vestibulum, at vulputate tellus lacinia. Ut interdum magna id velit lacinia, nec lobortis velit consequat. Ut et malesuada risus. In interdum eleifend est auctor tincidunt. Nulla facilisi. Proin faucibus ex euismod, porta purus ut, volutpat nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut mattis volutpat tempus. Vivamus condimentum velit in lacus ultrices ultricies. Morbi bibendum mauris ac pretium sagittis. Duis eget augue dapibus, convallis ante ut, accumsan ligula. Morbi cursus tellus viverra justo rutrum lobortis </div> <div class="my-bar"> this has to be on the top of any generic page </div>

I ended up adding a margin-top to fixed elements at render and on scroll events.我最终在渲染和滚动事件中为固定元素添加了margin-top

My main top bar is rendered as <div id="appbar-container">...</div> id (to avoid being pushed too).我的主顶部栏呈现为<div id="appbar-container">...</div> id(以避免被推送)。 Then I do it like that:然后我这样做:

const APPBAR_HEIGHT = 64;

const translateFixed = () => {
    Object.assign(document.body.style, {
      position: "relative",
      top: APPBAR_HEIGHT + "px",
    });

    for (let e of Array.from(document.body.getElementsByTagName("*"))) {
      if (
        e instanceof HTMLElement &&
        e.getAttribute("id") !== "appbar-container"
      ) {
        const position = getComputedStyle(e)
          .getPropertyValue("position")
          .toLocaleLowerCase();
        const top = e.getBoundingClientRect().top;

        if (position === "fixed" && top >= 0 && top <= APPBAR_HEIGHT) {
          e.style.marginTop = APPBAR_HEIGHT + "px";
          e.classList.add("appbar-offset");
        } else if (e.classList.contains("appbar-offset")) {
          e.style.marginTop = "0";
        }
      }
    }
};

  
// Initial push
translateFixed();

// Push on scroll
document.addEventListener("scroll", translateFixed);

I am not very proud of it though to be honest and I think there is room for improvement... But, well, it works.老实说,我并不为此感到自豪,我认为还有改进的余地……但是,它确实有效。

If you know the height of your bar, you can wrap all the content of the page with your own block, add some margin above it, and then add your bar using JS.如果你知道你的栏的高度,你可以用你自己的块包裹页面的所有内容,在它上面添加一些边距,然后使用 JS 添加你的栏。 Also it would be nice to set a background color to your bar.此外,为您的酒吧设置背景颜色会很好。 Here is an example using jQuery:下面是一个使用 jQuery 的例子:

 $('body').children().wrapAll('<div class="bar-render-content" />'); $('body').prepend('<div class="bar-render-top">Test bar</div>');
 .bar-render-top { top:0px; margin-top: 0px; position: fixed; z-index: 999999; width:100% !important; margin-bottom:50px; background-color: lightgrey; } .bar-render-content { margin-top:30px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <body> <div class="any"> Any text </div> <div class="content"> Lorem ipsum porttitor malesuada fusce adipiscing gravida eu sit tellus nam justo sem metus, elementum lorem adipiscing. Enim commodo malesuada porttitor ultricies diam, auctor congue sodales eros sem quisque, risus magna donec integer, lorem donec diam magna vivamus. Adipiscing bibendum pellentesque curabitur orci proin tempus sapien amet: lorem tempus. Quam nam, ipsum magna justo nam lorem nam, eu a fusce donec sed eget metus mauris ligula sagittis rutrum ultricies non at. Sed quisque lectus duis, ut magna malesuada: vivamus — in sagittis porta tempus: curabitur odio — magna risus, sapien — elementum, maecenas porttitor risus integer. Urna amet orci auctor elementum, magna justo arcu a auctor bibendum sem proin auctor amet justo metus morbi odio maecenas porttitor. Porta magna integer porttitor tellus eros nec ultricies magna rutrum curabitur, porttitor integer nam, sem non orci non nulla. </div> </body>

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

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