简体   繁体   中英

Try to get actual width & height of a element with jQuery

I'm trying to get the width & height of a element with jQuery. Now I have a function that wraps a span around the element and gets the size from the temporary span element.

HTML

<a id="test">click</a><br />
<div id="content" style="display:block">
    <div>Hello world</div>
</div>

<h3>Result:</h3>
<div id="result"></div>

JS

$( '#test' ).click ( function () {

    var size = elementSize ( '#content' );
    $( '#result' ).html ( size.width + ' x ' + size.height + ' px' );
} );

function elementSize ( elementId ) {

    var html_org = $( elementId ).html ();
    var html_calc = '<span>' + html_org + '</span>';
    $( elementId ).html( html_calc );

    var ret = {
        width: $( elementId ).find( 'span:first' ).width (),
        height: $( elementId ).find( 'span:first' ).height (),
    };

    $( elementId ).html( html_org );

    return ret;
}

An (not) working example: http://jsfiddle.net/KmeaC/1/

The only way to get the actual width & height of "Hello world" is to remove the div tags around it: http://jsfiddle.net/ycxTr/ . But that is not what I want :)

Anyone?

EDITED ANSWER

DEMO

$('#test').click(function () {

    var size = elementSize('#content');
    $('#result').html(size.width + ' x ' + size.height + 'px');
});

function elementSize(elementId) {

    var html_org = $(elementId).html();
    var $html_calc = $('<span>' + html_org + '</span>').css({
        position: 'absolute',
        top: -9999,
        left: -9999
    }).appendTo('body');



    var ret = {
        width: $html_calc.width(),
        height: $html_calc.height(),
    };
    $html_calc.remove();

    return ret;
}

When you copy a hidden element it's size is zero. Just unhide it for the calculation:

function elementSize ( elementId ) {
    ...
    $( elementId ).html( html_calc ).show();    
    var ret = {
        ...
    };    
    $( elementId ).html( html_calc ).hide();    
    ...    
    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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