我尝试了一些方法,但没有一个奏效。有人知道绕过这个的妙招吗?
<textarea placeholder='This is a line \n this should be a new line'></textarea>
<textarea placeholder='This is a line
should this be a new line?'></textarea> <!-- this works in chrome apparently -->
更新:它不工作在chrome。它只是textarea的宽度。
参见:http://jsfiddle.net/pdXRx/
稍微改进了Jason Gennaro的回答(见代码注释):
var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
if($(this).val() == placeholder){
// reset the value only if it equals the initial one
$(this).attr('value', '');
}
});
$('textarea').blur(function(){
if($(this).val() == ''){
$(this).attr('value', placeholder);
}
});
// remove the focus, if it is on by default
$('textarea').blur();
稍微改进了Jason Gennaro的回答(见代码注释):
var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
if($(this).val() == placeholder){
// reset the value only if it equals the initial one
$(this).attr('value', '');
}
});
$('textarea').blur(function(){
if($(this).val() == ''){
$(this).attr('value', placeholder);
}
});
// remove the focus, if it is on by default
$('textarea').blur();
我喜欢Jason Gennaro和Denis Golomazov的作品,但我想要一些在全球范围内更有用的东西。我已经修改了这个概念,这样它就可以添加到任何页面而不受影响。
http://jsfiddle.net/pdXRx/297/
<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>
<h2>Modified behaviors</h2>
<!-- To get simulated placeholder with New Lines behavior,
add the placeholdernl attribute -->
<textarea placeholdernl> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address' placeholdernl> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<h2>Standard behaviors</h2>
<textarea placeholder='Address'> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address'></textarea>
javascript非常简单
<script>
(function($){
var handleFocus = function(){
var $this = $(this);
if($this.val() === $this.attr('placeholdernl')){
$this.attr('value', '');
$this.css('color', '');
}
};
var handleBlur = function(){
var $this = $(this);
if($this.val() == ''){
$this.attr('value', $this.attr('placeholdernl'))
$this.css('color', 'gray');
}
};
$('textarea[placeholdernl]').each(function(){
var $this = $(this),
value = $this.attr('value'),
placeholder = $this.attr('placeholder');
$this.attr('placeholdernl', value ? value : placeholder);
$this.attr('value', '');
$this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>