我有一個在其中包含一些文本的按鈕。當你按下它時,文字會改變。這會使按鈕的寬度發生變化。這將是巨大的,如果能有這樣的過渡元素的寬度的變化:由內容更改導致的過渡元素大小
#el {
transition: width 150ms ease-out;
}
當然,這隻能當你明確地改變width
屬性。
有沒有人知道優雅的方式來達到這種效果? Here's a (yet-to-function) fiddle to hack away at。
我有一個在其中包含一些文本的按鈕。當你按下它時,文字會改變。這會使按鈕的寬度發生變化。這將是巨大的,如果能有這樣的過渡元素的寬度的變化:由內容更改導致的過渡元素大小
#el {
transition: width 150ms ease-out;
}
當然,這隻能當你明確地改變width
屬性。
有沒有人知道優雅的方式來達到這種效果? Here's a (yet-to-function) fiddle to hack away at。
嘗試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);
});
我想這是'不可能的,因爲瀏覽器無法獲得確切的目標寬度;讓我們假設它在轉換之前得到了值,但是那個時候,按鈕已經到達了寬度!也許是存在的,我們看不到它。 所以你需要一個初始寬度,你需要知道目標寬度太大,我們的js
隨着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);
});
這還挺正確的軌道上,但是它需要進行調整,使文本沒有按」 「流行」 - 我正在玩弄它。儘管如此,我真的很喜歡用最少的javascript來看看。 – namuol
非常有幫助,謝謝! (在我的例子中,我加了'white-space:nowrap;'來消除效果。) –