Pregunta

Como en el tema, ¿cómo se puede obtener el ancho total de un elemento, incluido su borde y relleno, usando jQuery?Tengo el complemento de dimensiones jQuery y al ejecutar .width() en mi DIV de 760 px de ancho y 10 px de relleno devuelve 760.

Quizás estoy haciendo algo mal, pero si mi elemento se manifiesta con 780 píxeles de ancho y Firebug me dice que tiene un relleno de 10 píxeles, pero llamar a .width() solo da 760, sería difícil ver cómo.

Gracias por cualquier sugerencia.

¿Fue útil?

Solución

[Actualizar]

La respuesta original fue escrita antes de jQuery 1.3, y las funciones que existían en ese momento no eran adecuadas por sí solas para calcular todo el ancho.

No fue JP dice correctamente, jQuery tiene las funciones ancho exterior y altura exterior que incluyen el border y padding por defecto, y también el margin si el primer argumento de la función es true


[Respuesta original]

El width El método ya no requiere dimensions complemento, porque se ha agregado al jQuery Core

Lo que debe hacer es obtener los valores de relleno, margen y ancho del borde de ese div en particular y agregarlos al resultado del width método

Algo como esto:

var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width

Dividir en varias líneas para hacerlo más legible

De esa manera siempre obtendrá el valor calculado correcto, incluso si cambia los valores de relleno o margen del CSS

Otros consejos

Cualquier otra persona que se encuentre con esta respuesta debe tener en cuenta que jQuery ahora (> = 1.3) tiene funciones outerHeight/outerWidth para recuperar el ancho incluyendo relleno / bordes, p. ej.

$(elem).outerWidth(); // Returns the width + padding + borders

Para incluir también el margen, simplemente pase true :

$(elem).outerWidth( true ); // Returns the width + padding + borders + margins

parece que externalWidth está roto en la última versión de jquery.

La discrepancia ocurre cuando

el div externo está flotando, el div interno tiene el ancho establecido (más pequeño que el div externo) el div interno tiene estilo = " margen: auto "

Solo por simplicidad, encapsulé la gran respuesta de Andreas Grech arriba en algunas funciones. Para aquellos que quieren un poco de felicidad de cortar y pegar.

function getTotalWidthOfObject(object) {

    if(object == null || object.length == 0) {
        return 0;
    }

    var value       = object.width();
    value           += parseInt(object.css("padding-left"), 10) + parseInt(object.css("padding-right"), 10); //Total Padding Width
    value           += parseInt(object.css("margin-left"), 10) + parseInt(object.css("margin-right"), 10); //Total Margin Width
    value           += parseInt(object.css("borderLeftWidth"), 10) + parseInt(object.css("borderRightWidth"), 10); //Total Border Width
    return value;
}

function  getTotalHeightOfObject(object) {

    if(object == null || object.length == 0) {
        return 0;
    }

    var value       = object.height();
    value           += parseInt(object.css("padding-top"), 10) + parseInt(object.css("padding-bottom"), 10); //Total Padding Width
    value           += parseInt(object.css("margin-top"), 10) + parseInt(object.css("margin-bottom"), 10); //Total Margin Width
    value           += parseInt(object.css("borderTopWidth"), 10) + parseInt(object.css("borderBottomWidth"), 10); //Total Border Width
    return value;
}

los mismos navegadores pueden devolver cadenas para el ancho del borde, en este análisis, devolverá NaN así que asegúrese de analizar el valor en int correctamente.

        var getInt = function (string) {
            if (typeof string == "undefined" || string == "")
                return 0;
            var tempInt = parseInt(string);

            if (!(tempInt <= 0 || tempInt > 0))
                return 0;
            return tempInt;
        }

        var liWidth = $(this).width();
        liWidth += getInt($(this).css("padding-left"));
        liWidth += getInt($(this).css("padding-right"));
        liWidth += getInt($(this).css("border-left-width"));
        liWidth += getInt($(this).css("border-right-width"));
$(document).ready(function(){     
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");   
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");         
});


<div class="width">Width of this div container without including padding is: </div>  
<div class="innerWidth">width of this div container including padding is: </div> 
<div class="outerWidth">width of this div container including padding and margin is:     </div>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top