2012-10-31 23 views

回答

2

嘗試this fiddle它使用jQuery。

$('button').click(function() { 
    var width = $(this).css('width'); 
    var height = $(this).css('height'); 
    $(this).html('Hello, World!'); 
    var newWidth = $(this).css('width'); 
    $(this).css({'width': width, 'height': height}); 
    $(this).animate({'width': newWidth}, 1000); 
});​ 
+0

這還挺正確的軌道上,但是它需要進行調整,使文本沒有按」 「流行」 - 我正在玩弄它。儘管如此,我真的很喜歡用最少的javascript來看看。 – namuol

+0

非常有幫助,謝謝! (在我的例子中,我加了'white-space:nowrap;'來消除效果。) –

0

我想這是'不可能的,因爲瀏覽器無法獲得確切的目標寬度;讓我們假設它在轉換之前得到了值,但是那個時候,按鈕已經到達了寬度!也許是存在的,我們看不到它。 所以你需要一個初始寬度,你需要知道目標寬度太大,我們的js

1

隨着Maurice's answer,按鈕的文本溢出到第二行,這是通過強制按鈕的高度,以原來的周圍工作高度。 相反,使用

button { 
    white-space: nowrap; 
} 

使按鈕的文本停留在一行並顯示,而在過渡。然後代碼不再具有處理按鈕的高度,所以它可以變得更簡單:

$('button').click(function() { 
    var width = $(this).css('width'); 
    $(this).text('Hello, World!'); 
    var newWidth = $(this).css('width'); 
    $(this).css({'width': width}); 
    $(this).animate({'width': newWidth}, 400); 
}); 

http://jsfiddle.net/2rr54vp2/1/