2013-03-09 2 views
1

내가하려는 것은 여백 크기와 내용 크기가 변경 되더라도 항상 내용을 컨테이너의 중심에 두는 것입니다. 이는 또한 콘텐츠의 여백과 너비를 감안할 때 컨테이너 크기가 자체적으로 변경되어야 함을 의미합니다. http://jsfiddle.net/jpY5n/jquery의 여백과 너비가있는 수학을 수행

function resizeContainer(size, distance) { 
var postWidth = size; 
var postApart = distance * 3; 
return postWidth + postApart; 
}; 
$(document).ready(function() { 
$('#container').width(resizeContainer($("#content").width(),$("#content").css("margin-left")); 
}); 

내가 이론적으로의 폭을 변경하는 내가 위해 설정 한 기능을 사용할 수 있습니다 여기에 출력을 제공하는 기능의 일반적인 셋업이있는 JS 바이올린과 경고입니다 게시물에서 알 수 있듯이 경계에서 수학을 볼 수는 없으므로 마진은 10px이 아니기 때문에 10이 아니므로 으로 돌아옵니다. NaN ... 마진 설정을하는 방법은 우리가 ßpx를 그냥 ß라고 말할 수 있겠습니까?

답변

1

당신은 '''px'를 교체 한 후 Number에 캐릭터 라인을 해석해 여백의 숫자 값을 얻을 수 있습니다 :

var margin = Number($('#content').css('margin-left').replace('px','')); 

Here's the updated Fiddle을.

HTML

<div id="container"> 
    <div id="content"></div> 
</div> 

자바 스크립트 (jQuery를)

function resizeContainer(size, distance) { 
    var postWidth = size * 2; 
    var postApart = distance * 3; 
    return postWidth + postApart; 
}; 
$(document).ready(function() { 
    alert("Container width should be set to " + $("#content").width() + " times 2 plus " + $("#content").css("margin-left") + " times 3"); 
    var width = Number($('#content').width()); 
    var margin = Number($('#content').css('margin-left').replace('px','')); 
    $('#content').width(resizeContainer(width,margin)); 
});