2017-07-25 33 views
1

我有以下代碼可以在單擊文本區域時最大化文本區域。當我點擊textarea時,如何將其恢復爲原始大小?如何在點擊時儘量減少文本區域

$('textarea').focus(function() { 
    $(this).animate({ height: "300px" }, 500); 
}); 
+1

[事件的內容](https://api.jquery.com/focusout /) – guradio

+0

見http://jsfiddle.net/tmnasim/sXbaT/ – Dexter

+0

你並不真的需要JavaScript的:http://jsfiddle.net/4hwrd3y4/1 –

回答

1

在這裏,你去與解決方案https://jsfiddle.net/k3aztqof/1/

$('textarea').focus(function() { 
 
    $(this).animate({ height: "300px" }, 500); 
 
}).focusout(function() { 
 
    $(this).animate({ height: "100px" }, 500); 
 
});
textarea{ 
 
    width: 500px; 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea></textarea>

+0

我會接受這個,因爲你已經給出了最完整的答案。感謝你和其他提供答案的人。 – Adders

+0

重要的是要提到,focusout並不是「focus」的「真正對」。 https://stackoverflow.com/questions/7858979/difference-between-focusin-focusout-and-focus-blur-with-example(當然,在這種情況下無所謂) –

1

該對focus事件是blurhttps://api.jquery.com/blur/),那麼你將要調整的模糊:

$('textarea').blur(function() { 
    $(this).animate({ height: "XXXpx" }, 500); 
}); 

編輯:但是你可能想使用一個唯一的CSS-解決方案:

textarea { 
    height:200px; 
} 
textarea:focus { 
    height:300px; 
} 

此外,您還可以使用一些CSS動畫技術來直觀地增強轉場。

+0

感謝您的迴應,我給你一個upvo TE。 – Adders

1
$('textarea').onblur = function() { 
    if(this.value === this.defaultValue) { 
    this.style.height = ''; 
} 
+1

感謝您的回覆,我已向您致謝。 – Adders

1
  1. 使用focusout

說明:綁定的事件處理程序 「事件的內容」 JavaScript事件。

$('textarea').focus(function() { 
 
    $(this).animate({ 
 
    height: "300px" 
 
    }, 500); 
 
}); 
 

 
$('textarea').focusout(function() { 
 
$(this).animate({ 
 
    height: "100px" 
 
    }, 500); 
 
})
textarea { 
 
    height: 100px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea></textarea>

+0

感謝您的回覆,我已向您致謝。 – Adders

1

不要用blur事件和設置高度與initial

$('textarea').focus(function() { 
 
    $(this).animate({ height: "300px" }, 500); 
 
}).blur(function(){ 
 
    $(this).animate({ height: "initial" }, 500); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<textarea>sss</textarea>

+1

感謝您的回覆,我已向您致謝。 – Adders

1

您可以用戶的jquery focusin()focusout()方法來增大和減小尺寸:

//increase size on focus in 
$('textarea').focusin(function() { 
    $(this).animate({ height: "300px" }, 500); 
}); 

//decrease size on focus out  
$('textarea').focusout(function() { 
    $(this).animate({ height: "initial" }, 500); 
}); 
+0

謝謝!樂於幫助。 –

0
<script> 
var org_height = $('textarea').height(); 

$('textarea').focus(function() { 
    $(this).animate({ height: "500px" }, 500); 
}); 

$('textarea').focusout(function() { 
    $(this).animate({ height: org_height }, 500); 
}); 

</script>