在textarea的占位符属性内插入换行符?

发布于 2021-02-02 16:56:32

我尝试了几种方法,但是都没有用。有谁知道解决这个问题的妙招?

<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中不起作用。只是文本区域的宽度。

关注者
0
被浏览
116
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    您可以做的是将文本添加为value,这要注意换行符\n

    $('textarea').attr('value', 'This is a line \nthis should be a new line');
    

    然后,您可以将其移除,focus然后将其重新应用(如果为空)blur。像这样

    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);
        }    
    });
    

    不是纯CSS也不 干净, 但是可以解决问题。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看