简体   繁体   中英

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. For example, think of a website with wp-admin bar and a menubar fixed on top.

I am creating a plugin & so I cannot modify the website's code, but can override styles.

Here is my 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. So I cannot add site-specific styles.

Ideally, this should behave like the mozbar chrome addon, which adds a topbar as an 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.

My main top bar is rendered as <div id="appbar-container">...</div> id (to avoid being pushed too). 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. Also it would be nice to set a background color to your bar. Here is an example using 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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