jQuery:textarea默认值在点击时消失
我想要一个带有一些默认文本的textarea。 当用户单击textarea时,应删除默认文本。 如何让点击时textarea的值消失?
我希望它完全像这样, http://www.webune.com/forums/20101025cgtc.html
但我希望它在jQuery中完成。
我使用它作为它更通用 – 它将清除焦点上的元素值,但如果为空则返回元素的值为默认值。
$("#textarea") .focus(function() { if (this.value === this.defaultValue) { this.value = ''; } }) .blur(function() { if (this.value === '') { this.value = this.defaultValue; } });
即使没有JavaScript,您也可以使用placeholder
属性来完成此操作。
但是你应该知道并非每个浏览器都支持它。 在这种情况下,您可以使用例如此插件: http : //plugins.jquery.com/project/input-placeholder
这应该工作:
$('#txt') .focusin(function() { if ( this.value == 'Write something...' ) { this.value = ''; } }) .focusout(function() { if ( this.value == '' ) { this.value = 'Write something...'; } });
现场演示: http : //jsfiddle.net/g7UKN/1/
更新:
这应该这样做:
$('#txt') .each(function() { $(this).data('default', this.value); }) .focusin(function() { if ( this.value == $(this).data('default') ) { this.value = ''; } }) .focusout(function() { if ( this.value == '' ) { this.value = $(this).data('default'); } });
现场演示: http : //jsfiddle.net/g7UKN/2/
非常简单的非jQuery依赖解决方案:
$('#textarea').click(function(){ if($(this).val() == "This should be removed.."){ $(this).val() = ""; } });
//编辑
var defaultTextAreaValue = "This should be removed.."; $('#textarea').focus(function(){ if($(this).val() == defaultTextAreaValue){ $(this).val(""); } }); $('#textarea').blur(function(){ if($(this).val() == "" || $(this).val() == defaultTextAreaValue){ $(this).val(defaultTextAreaValue); } });
试试下面的片段。 首次单击文本区域时,它会清空内容。
$('#textarea').focus(function(){ $(this).empty(); });
你需要两个处理程序,一个用于元素获得焦点,一个用于何时失去它。 当它获得焦点时,检查该值是否仅为空格字符,如果是,则将值设置为默认值。
$('#textarea').focus( function(){ var $this =$(this); if($this.val() == 'This should be removed..'){ $this.val(''); } }).blur(function() { var $this = $(this); if ($this.val().match(/^\s*$/) { // matches only spaces or nothing $this.val('This should be removed..'); } });
如果有人想在ajax加载的textareas上做这个技巧你可以用.live()
事件来实现这个;)
$('#textarea').live('focusin',function () { if (this.value === 'leDefault ...') { this.value = ''; } }); $('.larger').live('focusout',function () { if (this.value === '') { this.value = 'leDefault'; } });