簡體   English   中英

jQuery.height() function 返回假值

[英]jQuery .height() function returns false value

我試圖通過獲取元素高度並在父 div 上設置它來設置動態高度但是當我使用 jQuery.height() function 返回錯誤值時:例如:-

<div style="height: 300px">
    this is outer div
    <div style="position:absolute; height: 400px">
        this is inner div of which i need to read height and set to its parent
    </div>
</div>

我的 jquery 代碼

var innerDiv = $("#innerDiv").height();
console.log(innerDiv);
//this is suppose to give 400 but on button click it show 845 and but on second click it shows 400
$("#outerDiv").css({'height': `${innerDiv}px`})

您的代碼沒有任何問題,除了缺少 ID,事實上,如果您添加id="outerDiv"id="innerDiv" ,一切都會正常進行。

也許您的原始腳本中還有其他內容將內部 div 高度拉伸到 845。

 var innerDiv = $("#innerDiv").height(); console.log(innerDiv); //this is suppose to give 400 but on button click it show 845 and but on second click it shows 400 $("#outerDiv").css({ height: `${innerDiv}px` });
 div { /* a black outline to see the DIVs */ outline: 1px solid black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="outerDiv" style="height: 300px"> this is outer div <div id="innerDiv" style="position:absolute; height: 400px"> this is inner div of which i need to read height and set to its parent </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM