jQuery + CSS. How do I compute height and width of innerHTML?

五迷三道 提交于 2019-12-06 10:05:29

问题


I have a typical parent-child div hierarchy for a Web project using jQuery. The child css has not height, this allows it to expand and contract based on the height of the innerHTML. I am programmatically stuffing HTML markup into the innerHTML property of the child.

I want to set the height of the parent to match the height of the child after the child has it's markup. How do I do this? I tried:

    childDiv.innerHTML = content;
    childDivObject = $(childDiv);

     parentDivObject = $(parentDiv);
     parentDivObject.css({
        "height" : childDivObject.height() + "px"
    });

But this did not work. What am I missing?

UPDATE 0

More context. This code is for a popup that appears/disappears with a user tap. Here is the css. There is just not a lot going on here:

// parent
.parent {
    position: absolute;
    top: 0;
    left: 0;
    width: 350px;
    display: none;
}

// child
.child {
    position: absolute;
    top: 5px;
    left: 5px;
    right: 25px;
}

Could the fact that the parent has display:none be part of the problem? I am using the jQuery show()/hide() methods if that is relevant.


回答1:


Change this:

"height" : childDivObject.height() + "px"

to this:

"height" : childDiv.height() + "px"

Looks like you are trying to get the height of the content rather than the div itself.




回答2:


Got it. Because jQuery toggles the css display property to hide/show the popup.

The answer is to do this:

    parentDivObject.css({
        "left": left + "px",
        "top" : top  + "px"
    }).show();

    parentDivObject.css({
        "height": childDivObject.height() + "px"
    });

I set the height after the jQuery show() method which toggles display and then height becomes valid. It's not pretty, but it works. Cheers.




回答3:


Normally you would use a callback, but html() doesn't have one, but there's something else, called promise.

jquery html() callback function http://digitizor.com/2013/08/03/jquery-html-callback-function-using-promise/

   $('#divId').html(someText).promise().done(function(){
        //your callback logic / code here
    });


来源:https://stackoverflow.com/questions/26058532/jquery-css-how-do-i-compute-height-and-width-of-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!