简体   繁体   English

如何获取一个元素的变化高度值并将其作为 CSS “顶部”值返回 jQuery 中的另一个元素?

[英]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.我有一个名为“header”的 div,当用户向下滚动页面时,它会缩小它的高度。

Under the "header" I have another div called "menu".在“标题”下,我有另一个名为“菜单”的 div。 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.我希望菜单是“绝对位置”,其“顶部:xy”值与“标题”的高度相同,即使它发生变化。

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". ...我可以根据“标题”的初始高度动态调整菜单的“顶部:xy”值。

But I need to automatically adjust it when the height of the "header" changes.但是当“标题”的高度发生变化时,我需要自动调整它。

Can I accomplish it with jQuery?我可以用 jQuery 完成它吗?

Thank you so much in advance.非常感谢你。

Your jQuery code is correct to fetch header height and use the value to adjust position top.您的 jQuery 代码正确获取 header 高度并使用该值调整 position 顶部。 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)
});

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

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