2017-02-14 64 views
-1

我有一个用于写入消息的文本框。我想用div显示写在这个文本框中的文本。我这样做,但只有文本是显示,但格式不是当我写入使用输入,然后在预览文本是相互显示。未在下一行中显示。准确地获取文本框中写入的文本

function limiter(){ 
 
    var tex = document.SendSms.msg.value; 
 
    $(".speech").html(tex); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<form name='SendSms'> 
 
<textarea name="msg" id="msg" class="txtareabox" wrap='physical' onkeyup="limiter()" required ></textarea> 
 

 
<div id="mobilescreen"> 
 
    <div id="mobiletext"> 
 
    <p class="speech">See your preview here.. </p> 
 
    </div> 
 
</div>

+0

您需要更换'enter'('\ N','\ r ','\ n \ r''\ r \ n')与'
',但请注意样式不可编辑。其他方面,你做'var text =“

”+ textarea.value +“

”'并用'

'替换'enter'并将其添加'div.innerHTML = text' – DomeTune

回答

0

这里是ypur问题的aproximation。认为textarea中的\ n必须翻译为"<br/>"

https://jsfiddle.net/qu0mcsd6/

这里是js代码:

function addText(){ 
    var tex = document.SendSms.msg.value; 
    tex = tex.replace(/\n/g, "<br>"); 
    $(".speech").html(tex); 
} 
$('#poner').click(addText); 

感谢

0

form标签的name属性已被废弃,不应该使用(cf. spec),id应改为使用。

function limiter() { 
    var tex = $("#msg").val(); // get the value of the form input (textarea) and store it in tex variable 
    $(".speech").html(tex); // set the value as innerHTML of the element(s) with 'speech' class 
} 
+3

尝试一下,然后发布if它的工作原理.. –

+0

虽然这段代码片断是受欢迎的,并且可以提供一些帮助,但它会[如果包括解释](/ meta.stackexchange.com/q/114762)* how *和*会大大改进*解决了这个问题。请记住,你正在为将来的读者回答这个问题,而不仅仅是现在问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 –

0

你应该<br>在返回的值替换\n

document.SendSms.msg.value.replace(/\n/g,"<br>"); 

注:由于您使用jQuery的你可以定义js代码里面的事件,我建议使用input事件,而不是keyup的,因为当你跟踪用户输入

$('#msg').on('input', function(){ 
    $(".speech").html($(this).val().replace(/\n/g,"<br>")); 
}) 

希望这有助于更高效。

$('#msg').on('input', function(){ 
 
    $(".speech").html($(this).val().replace(/\n/g,"<br>")); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="SendSms"> 
 

 
    <textarea name="msg" id="msg" class="txtareabox" wrap='physical' required ></textarea> 
 
    and the div in which i want to show my preview: 
 

 
</form> 
 

 
<div id="mobilescreen"> 
 
    <div id="mobiletext"> 
 
    <p class="speech">See your preview here.. </p> 
 
    </div> 
 
</div>

+0

防止使用内联'onkeyup'确实更好。 –

0

只需使用String.replace()到\ r \ n更改为<br>。 这里是你如何做到这一点的ES6,只是使用VAR,而不是常量,让向后兼容性

const textarea = document.querySelector("textarea"); 
 
const div = document.querySelector("div"); 
 
let text = textarea.innerHTML; 
 

 
text = text.replace(/\r?\n/g, '<br>'); 
 

 
div.innerHTML = text;
<textarea> 
 
Line 1 
 
line2 
 
line3 
 
</textarea> 
 
<div></div>

+0

在答案的第一行中,您忘记使用''来跳过'
'代码。 –