Pergunta

Como no assunto, como se pode obter a largura total de um elemento, incluindo a sua fronteira e preenchimento, usando jQuery? Eu tenho o jQuery dimensões plugin, e correndo .width () em meus 760px de largura, 10px preenchimento DIV retorna 760.

Talvez eu estou fazendo algo errado, mas se meu elemento se manifesta como 780 pixels de largura e Firebug diz-me que há 10px preenchimento nele, mas chamando .width () só dá 760, eu seria duramente pressionado para ver como.

Obrigado por todas as sugestões.

Foi útil?

Solução

[Update]

A resposta original foi escrito antes do jQuery 1.3, e as funções que existiam na época em que não é adequada por si para calcular a largura inteira.

Agora, como JP afirma corretamente, jQuery tem as funções outerWidth e outerHeight que incluem a border e padding por padrão, e também o margin se o primeiro argumento da função é true


[resposta Original]

O método width não requer mais o plugin dimensions, porque foi adicionado ao jQuery Core

O que você precisa fazer é obter a largura valores de preenchimento, margem e fronteiriças do que div particular e adicioná-los ao resultado do método width

Algo parecido com isto:

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

dividido em várias linhas para torná-lo mais legível

Dessa forma, você sempre terá o valor calculado correta, mesmo se você mudar os valores de preenchimento ou margem do css

Outras dicas

Qualquer outra pessoa deparando com esta resposta deve observar que jQuery agora (> = 1.3) tem outerHeight / outerWidth funções para recuperar a largura incluindo padding / fronteiras, por exemplo,

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

Para incluir a margem, bem como, simplesmente passar true :

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

parece com outerWidth é quebrado na última versão do jQuery.

A discrepância acontece quando

o div externa é lançada, a div interna tem o conjunto de largura (menor do que o exterior div) o div interna tem style = "margin: auto"

Apenas para simplificar I encapsulado grande resposta de Andreas Grech acima em algumas funções. Para aqueles que querem um pouco de cut-and-paste felicidade.

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;
}

mesmos navegadores pode retornar string para largura da borda, neste parseInt retornará NaN por isso certifique-se de valor de análise para int corretamente.

        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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top