문제

주제에서와 같이, jQuery를 사용하여 테두리 및 패딩을 포함하여 요소의 총 너비를 어떻게 얻을 수 있습니까? jQuery Dimensions 플러그인이 있고 760px wide, 10px 패딩 DIV 760에서 .width ()를 실행합니다.

아마도 내가 뭔가 잘못하고 있지만 내 요소가 780 픽셀 너비로 나타나고 Firebug가 10px 패딩이 있다고 말하지만 .width ()에게 전화를 걸면 760만을 부여하면 방법을 알기가 어려울 것입니다.

제안 해주셔서 감사합니다.

도움이 되었습니까?

해결책

업데이트

원래의 답변은 jQuery 1.3 이전에 작성되었으며, 전체 너비를 계산하기에 적합하지 않은 당시에 존재했던 기능.

이제 JP jQuery에는 기능이 올바르게 나타납니다 외부 그리고 외부 여기에는 border 그리고 padding 기본적으로, 그리고 또한 margin 함수의 첫 번째 인수가 있다면 true


원본 답변

그만큼 width 메소드에는 더 이상 필요하지 않습니다 dimensions 플러그인은 다음에 추가 되었기 때문에 jQuery Core

당신이해야 할 일은 특정 div의 패딩, 마진 및 테두리 너비 값을 얻고 결과에 추가하는 것입니다. width 방법

이 같은:

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

더 읽기 쉬운 여러 줄로 나뉘어진다

그렇게하면 CSS에서 패딩 또는 마진 값을 변경하더라도 항상 올바른 계산 값을 얻게됩니다.

다른 팁

이 답변에 걸려 넘어지는 다른 사람은 지금 jQuery (> = 1.3)가 outerHeight/outerWidth 패딩/경계를 포함하여 너비를 검색하는 기능, 예를 들어

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

여백을 포함 시키려면 간단하게 통과하십시오 true:

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

최신 버전의 jQuery에서 외부면이 깨진 것 같습니다.

불일치는 언제 발생합니다

외부 디바리가 떠 다니고 내부 Div에는 너비 세트가 있습니다 (외부 div보다 작음) 내부 div는 style = "margin : auto"를 갖습니다.

단순화를 위해 나는 일부 기능으로 위의 Andreas Grech의 위대한 대답을 캡슐화했습니다. 약간의 컷 앤 페이스트 행복을 원하는 사람들에게.

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

동일한 브라우저는 테두리 너비에 대한 문자열을 반환 할 수 있습니다.

        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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top