如何使标签使用内部文本的大小?
我的意思是我该怎么做,即使文本太长也会显示全文而不是滚动条?
答案 0 :(得分:1)
James Padolsey为auto resizing textareas提供了一个非常漂亮的jQuery脚本(该脚本已经不在互联网上了,所以这里有个备份)。
/*
* jQuery autoResize (textarea auto-resizer)
* @copyright James Padolsey http://james.padolsey.com
* @version 1.04
*/
(function($){
$.fn.autoResize = function(options) {
// Just some abstracted details,
// to make plugin users happy:
var settings = $.extend({
onResize : function(){},
animate : true,
animateDuration : 150,
animateCallback : function(){},
extraSpace : 20,
limit: 1000
}, options);
// Only textarea's auto-resize:
this.filter('textarea').each(function(){
// Get rid of scrollbars and disable WebKit resizing:
var textarea = $(this).css({resize:'none','overflow-y':'hidden'}),
// Cache original height, for use later:
origHeight = textarea.height(),
// Need clone of textarea, hidden off screen:
clone = (function(){
// Properties which may effect space taken up by chracters:
var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
propOb = {};
// Create object of styles to apply:
$.each(props, function(i, prop){
propOb[prop] = textarea.css(prop);
});
// Clone the actual textarea removing unique properties
// and insert before original textarea:
return textarea.clone().removeAttr('id').removeAttr('name').css({
position: 'absolute',
top: 0,
left: -9999
}).css(propOb).attr('tabIndex','-1').insertBefore(textarea);
})(),
lastScrollTop = null,
updateSize = function() {
// Prepare the clone:
clone.height(0).val($(this).val()).scrollTop(10000);
// Find the height of text:
var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
toChange = $(this).add(clone);
// Don't do anything if scrollTip hasen't changed:
if (lastScrollTop === scrollTop) { return; }
lastScrollTop = scrollTop;
// Check for limit:
if ( scrollTop >= settings.limit ) {
$(this).css('overflow-y','');
return;
}
// Fire off callback:
settings.onResize.call(this);
// Either animate or directly apply height:
settings.animate && textarea.css('display') === 'block' ?
toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
: toChange.height(scrollTop);
};
// Bind namespaced handlers to appropriate events:
textarea
.unbind('.dynSiz')
.bind('keyup.dynSiz', updateSize)
.bind('keydown.dynSiz', updateSize)
.bind('change.dynSiz', updateSize);
});
// Chain:
return this;
};
})(jQuery);
Here's another by Louis Lazeris,其中还包括其他选项的链接。它就像您可能希望的那样起作用。文本区域以正常的合理大小开始。随着您键入越来越多的内容,文本区域将扩展为包括所有文本,而不是像默认那样触发滚动条。
该插件具有多种选择,但最简单的是,您只需加载插件文件jQuery,并按以下方式调用它即可:
$('textarea').autoResize();
这里的另一个技巧是根本不使用a,而是使用。它将自动增长,根本不需要花哨的JavaScript帮助-除非它不再是真正的表单元素,所以您将需要JavaScript来提取/发送值。