Get actual width and height of a component

前端 未结 7 980
离开以前
离开以前 2021-02-12 22:49

We\'re facing a fairly scary issue in JavaScript that none of us seems to be quite capable of resolving:

How do we get the width and height of a DOM element, including

相关标签:
7条回答
  • 2021-02-12 23:43

    Don't know if that helps, but since you asked for any answer :) here is what I have.

    I had a similar issue where I wanted to have nice jQuery effect to resize an HTML container to "auto" height and width according to it's inner content. The idea is still similar to what some people already mentioned here: you have a container somewhere "off the screen", you put your stuff there, measer the dimentions and delete it. So here is the function I have found here

    jQuery.fn.animateAuto = function(prop, speed, callback) {
        var elem, height, width;
        return this.each(function(i, el) {
            el = jQuery(el), elem = el.clone().css({
                "height" : "auto",
                "width" : "auto"
            }).appendTo("body");
            height = elem.css("height"), width = elem.css("width"), elem.remove();
    
            if (prop === "height")
                el.animate({
                    "height" : height
                }, speed, callback);
            else if (prop === "width")
                el.animate({
                    "width" : width
                }, speed, callback);
            else if (prop === "both")
                el.animate({
                    "width" : width,
                    "height" : height
                }, speed, callback);
        });
    };
    

    This code has a little more than you need but the part that you might be interested in is this:

    elem = el.clone().css({
                    "height" : "auto",
                    "width" : "auto"
    }).appendTo("body");
    height = elem.css("height")
    width = elem.css("width")
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题