2013-03-27 127 views
0

我適應一個文本自動增長的插件給我使用的情況下騰出空間兄弟姐妹

http://jsfiddle.net/hY73a/

的變化是,它應該是單線從開始,並應留有餘地,兄弟姐妹

我是這樣計算兄弟姐妹的寬度,但我一定是做錯了,因爲你可以看到兩個兄弟姐妹不適合

var siblings = $self.siblings(); 
var siblingsWidth = 0; 
for(var i = 0; i < siblings.length; i++) 
    siblingsWidth += $(siblings[i]).outerWidth(); 

然後設置類似

$self.css({"max-width": $self.parent().innerWidth() - siblingsWidth }); 

回答

0

最大寬度發生這種情況的原因是因爲span元素display: inline元素,瀏覽器把它們周圍的空間,因爲它會爲文本節點。這會導致這些組件佔用的空間量爲它們的寬度加上它們之間的空間量。

爲了演示這一點,我刪除了HTML中的span元素之間的所有間距。

<div style="width: 200px; border: solid black 1px"> 
    <textarea></textarea><span>SibOne</span><span>SibTwo</span> 
</div> 

其中需要注意的另一個領域是,原來的代碼不是在寬度的由textarea的盒子模型(例如,空白,邊框填充)的其它部件用完的量因式分解。

// Get the amount of horizontal space used up by the textarea margin, border, and padding 
var selfUnfactoredWidth = parseInt($self.css('margin-left'), 10) 
    + parseInt($self.css('margin-right'), 10) 
    + parseInt($self.css('border-left-width'), 10) 
    + parseInt($self.css('border-right-width'), 10) 
    + parseInt($self.css('padding-left'), 10) 
    + parseInt($self.css('padding-right'), 10); 

$self.css({ 
    "max-width": $self.parent().innerWidth() - selfUnfactoredWidth - siblingsWidth 
}); 

DEMO

或者,你可以使用box-sizing修改默認CSS box model

textarea { 
    resize: none; 
    border: solid black 1px; 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    box-sizing: border-box; 
} 

這樣做可以讓你忽略邊框和填充寬度從之前的改變盒模型會照顧它。

// Get the amount of horizontal space used up by the textarea margin, border, and padding 
var selfUnfactoredWidth = parseInt($self.css('margin-left'), 10) 
    + parseInt($self.css('margin-right'), 10); 

$self.css({ 
    "max-width": $self.parent().innerWidth() - selfUnfactoredWidth - siblingsWidth 
}); 

DEMO (Using box-sizing)