简体   繁体   English

使用 jQuery 根据 div 高度动态更新上边距

[英]Dynamically update top margin based on div height using jQuery

I'm trying to dynamically change the top margin size as the height of another div changes.我正在尝试随着另一个 div 的高度变化动态更改上边距大小。 The script below works but it's using the height of the body as it changes.下面的脚本有效,但它在变化时使用身体的高度。 How do I update the script to target the height of a specific div?如何更新脚本以针对特定 div 的高度?

updateDivsMargins();
$(window).resize(updateDivsMargins);

function updateDivsMargins() {
    $('div.mobile-menu').each(function () {
        $(this).css({
            'margin-top': ($(this).height()),
        });
    });
}
 $(document).ready(function() {
    updateDivsMargins();
    $(window).resize(updateDivsMargins);

    function updateDivsMargins() {
        $('div.mobile-menu').each(function () {
            $(this).css({
                'margin-top': ($('#specificDiv').height()),
            });
        });
    }
});

The function will iterates through all divs with the class name "mobile-menu" and sets the 'margin-top' CSS property to the height of the div with the id "specificDiv" function 将遍历所有名称为“mobile-menu”的 class 的 div,并将“margin-top”CSS 属性设置为 ID 为“specificDiv”的 div 的高度

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

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