2013-03-09 59 views
1

我想要做的是讓內容始終位於容器的中心,即使邊距大小和內容大小發生變化。這也意味着,考慮到內容的邊距和寬度,容器的大小必須自行改變。這裏是具有功能的通用的建立,讓輸出一個js小提琴和警報: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")); 
}); 

我理論上可以使用我爲了設置功能改變的寬度但它不能計入利潤率的數學,因爲如您在提示中看到的那樣,利潤率爲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> 

的JavaScript(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)); 
}); 
相關問題