I have created a form having a "textarea" which has a "placeholder" attribute.
<textarea placeholder="Enter Your Text"></textarea>
What I want is, I want to display this placeholder text on every line after 'Enter' key is pressed. So that I can use it for a good UI.
Ex.
|Enter Your Text
As if I entered "Hello" and pressed Enter key, It should be like:
Hello
|Enter Your Text
Or As if I entered "Hello" and pressed Enter key thrice,It should be like:
Hello
|Enter Your Text
Can Anyone give solution for this!!
Thank You!
答案 0 :(得分:1)
If I'm not wrong and I've understood what you want, you can do something like this (jsFiddle):
// this example needs to be improved if you want to use in production, but I think this is a way to achieve it
$('textarea').on('keypress', function(e){
// store the placeholder
var ph = $(this).attr('placeholder');
// store the current value
var current_value = $(this).val();
// delete the placeholder from the current value (if exists)
$(this).val(function(){ return arguments[1].replace(ph, ''); });
// when pressing enter
if( e.keyCode === 13 ) {
// if there are line breaks, remove any existing placeholder and append the new one
if( /\n/g.test(current_value) ) $(this).val(current_value.replace(ph, '') + ph);
// otherwise just append the value with the placeholder
else $(this).val(current_value + ph);
// now move the cursor to the last position less the placeholder length
var mv = $(this).val().length - ph.length;
$(this)[0].setSelectionRange(mv, mv);
}
});
答案 1 :(得分:-1)
您可以做的是将文本添加为值,该值取决于换行符\ n。
$('textarea').attr('value', 'This is a line \nthis should be a new line');
然后你可以在焦点上将其移除并将其应用于模糊处理(如果为空)。像这样的东西
var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
if($(this).val() === placeholder){
$(this).attr('value', '');
}
});
$('textarea').blur(function(){
if($(this).val() ===''){
$(this).attr('value', placeholder);
}
});
JsFiddle 不是纯粹的CSS,也不是干净但是有把戏。
答案 2 :(得分:-1)