简体   繁体   中英

Fixed positioned element Top

I have a div with position="fixed", I need to get the Top of the div with respect to the browser window top edge using JavaScript, I need the top of the div regardless of the page scroll.

I have tried offsetTop, but it returns the Top with respect to the document, not the browser.

Use getBoundingClientRect(), it gets the position relative to the viewport.

var el = document.querySelector('div');
var top = el.getBoundingClientRect().top;

MDN Docs

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