jQuery: Get height of hidden element in jQuery

后端 未结 14 2367
南方客
南方客 2020-11-22 09:49

I need to get height of an element that is within a div that is hidden. Right now I show the div, get the height, and hide the parent div. This seems a bit silly. Is there a

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:18

    I've actually resorted to a bit of trickery to deal with this at times. I developed a jQuery scrollbar widget where I encountered the problem that I don't know ahead of time if the scrollable content is a part of a hidden piece of markup or not. Here's what I did:

    // try to grab the height of the elem
    if (this.element.height() > 0) {
        var scroller_height = this.element.height();
        var scroller_width = this.element.width();
    
    // if height is zero, then we're dealing with a hidden element
    } else {
        var copied_elem = this.element.clone()
                          .attr("id", false)
                          .css({visibility:"hidden", display:"block", 
                                   position:"absolute"});
        $("body").append(copied_elem);
        var scroller_height = copied_elem.height();
        var scroller_width = copied_elem.width();
        copied_elem.remove();
    }
    

    This works for the most part, but there's an obvious problem that can potentially come up. If the content you are cloning is styled with CSS that includes references to parent markup in their rules, the cloned content will not contain the appropriate styling, and will likely have slightly different measurements. To get around this, you can make sure that the markup you are cloning has CSS rules applied to it that do not include references to parent markup.

    Also, this didn't come up for me with my scroller widget, but to get the appropriate height of the cloned element, you'll need to set the width to the same width of the parent element. In my case, a CSS width was always applied to the actual element, so I didn't have to worry about this, however, if the element doesn't have a width applied to it, you may need to do some kind of recursive traversal of the element's DOM ancestry to find the appropriate parent element's width.

提交回复
热议问题