简体   繁体   English

根据Parent高度和Top position value值调整子元素高度

[英]Adjust child element height based on Parent height and Top position value value

I am having parent with fixed height (400px) and child div height more than parent div height (400px - child div's top value) should be based on below conditions.我有固定高度(400px)的父级和高于父级 div 高度(400px - 子级 div 的最高值)的子级 div 高度应该基于以下条件。

  • Parent div height - child div's top position value (Eg: 40px in this scenario)父 div 高度 - 子 div 的顶部 position 值(例如:在这种情况下为 40px)

So, Finally Child div height should be 360px (400px - child div's top value of -40px)因此,最终子 div 高度应为 360px(400px - 子 div 的最高值为 -40px)

HTML: HTML:

<div class="parent">
    <div class="child">
        Parent Height: <span id="parentHeight"></span><br>
        Distance from top: <span id="distanceFromTop"></span><br>
        Child Height: <span id="childHeight"></span><br>
    </div>
</div>

Script:脚本:

var __parentHeight = $('.parent').height();
var __distanceFromTop = $('.parent').offset().top - $('.child').offset().top;
var __finalHeight = parseInt(__parentHeight) - parseInt(__distanceFromTop);

$('#parentHeight').html(__parentHeight + 'px');
$('#distanceFromTop').html(__distanceFromTop + 'px');
$('#childHeight').html(__finalHeight + 'px');

$('.child').css('height', __finalHeight + 'px');

jsFiddle jsFiddle

Expected:预期的:

在此处输入图像描述

What I am getting is:我得到的是:

在此处输入图像描述

Update your final height calculation like that => var __finalHeight = parseInt(__parentHeight) - parseInt(__distanceFromTop);像这样更新你的最终高度计算 => var __finalHeight = parseInt(__parentHeight) - parseInt(__distanceFromTop);

you are setting position not margin or padding.您正在设置 position 不是边距或填充。 to get top position pixel use $('.child').position().top;要获得顶部 position 像素,请使用$('.child').position().top; this will get you that 40px position top.这将为您提供 40px position 顶部。

here is fiddle jsfiddle这是小提琴jsfiddle

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

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