正如您所看到的,当用户输入文本时,我试图增加文本字段的高度,当用户点击离开时(元素失去焦点),我将其变小。
有没有更简单的方法来编写以下代码?
简单的 HTML 输入字段:
<input type="text" />
jQuery:
$(document).ready(function() {
$('input').on('focus', function() {
$(this).height('20px');
});
$('input').on('blur', function() {
$(this).height('12px');
});
});
最佳答案
仅使用 CSS 即可更有效地完成此操作,但使用 jQuery,您可以使用事件委托(delegate)。
$(document).on('focus blur', 'input', function(e) {
$(this).height(e.type === 'focusin' ? '20px' : '12px');
})
为了完整起见,这里是 CSS 解决方案:
input {
height: 12px;
}
input:focus {
height: 20px;
}
关于javascript - jQuery onfocus 和 onblur 事件缩小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503677/