简体   繁体   中英

How to get a changing height value of one element and return it as a CSS "top" value on another element in jQuery?

I have a div called "header" that shrinks its height when the user scroll down the page.

Under the "header" I have another div called "menu". I want the menu to be "position absolute" with a "top: xy" value that is the same as the height of the "header", even when it changes.

With:

var height_of_div1 = $(".header").css('height');
$(".menu").css('top',height_of_div1);

...I can dynamically adjust the menu's "top: xy" value based on the initial height of the "header".

But I need to automatically adjust it when the height of the "header" changes.

Can I accomplish it with jQuery?

Thank you so much in advance.

Your jQuery code is correct to fetch header height and use the value to adjust position top. But you need to apply it with scroll listener.

window.addEventListener('scroll',function(){
  var height_of_div1 = $("#header").css('height');
  $('.menu').css('top', height_of_div1)
});

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