JavaScript-更新< textarea>在特定条件下的值,并将其附加到< div> [英] JavaScript - updating <textarea> value under certian conditions and append it to a <div>
问题描述
我在 div
后面附加了一个pagaraph( p
),它显示< textarea>
值,并且效果很好.br>< textarea>
应该是页面的一部分,允许用户向文本内容添加新行,就像我们键入< br>
的方式一样在 textarea
中换行.
但是,由于他们不知道该怎么做,因此我尝试通过以下方式使他们更轻松:
I have a pagaraph (p
) appended to a div
, that shows <textarea>
value, and it works well.
The <textarea>
supposed to be a part of a page that allows the users to add new lines to the text content, exactly like how we can type <br>
for a new line in textarea
.
But since they don't know how to do that I'm trying to make it easy for them by:
(两次键入加号++ ++ OR 按键盘上的Enter键)
(typing plus sign twice ++ OR pressing Enter on the keyboard)
两者都应在输入(onkeyup)
时自动添加< br>
标记...
我需要您的帮助,反正谢谢您.
Both should add a <br>
tag automatically while typing (onkeyup)
...
I need your help please and thank you anyway.
var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;
textarea.onkeyup = function(){
currentText = textarea.value;
var previewAsString = "<p class='p-preview'>" + currentText + "</p>"
textareaPreview.innerHTML = previewAsString;
};
textarea {
width: 300px;
height: 80px;
resize: vertical;
}
<div class="block">
<textarea id="textarea" placeholder="Type here.."></textarea>
</div>
<div class="block">
<div class="textarea-preview"></div>
</div>
推荐答案
已解决
填写 textarea
进行测试:
SOLVED
Fill the textarea
for testing:
var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;
textarea.onkeyup = function(){
currentText = textarea.value;
currentText = newLine(currentText);
currentText = boldText(currentText);
currentText = italicText(currentText);
currentText = underlineText(currentText)
var previewAsString = "<p class='p-preview'>" + currentText + "</p>"
textareaPreview.innerHTML = previewAsString;
};
function newLine(text){
var newLineJs = /\+\+/g;
var newLineHTML = "<br>";
return text.replace(newLineJs, newLineHTML);
}
function boldText(text){
var boldJs = /\*\*(\S(.*?\S)?)\*\*/gm;
return text.replace(boldJs, '<strong>$1</strong>');
}
function italicText(text){
var iJs = /\^\^(\S(.*?\S)?)\^\^/gm;
return text.replace(iJs, '<i>$1</i>');
}
function underlineText(text){
var uJs = /\*\-(\S(.*?\S)?)\-\*/gm;
return text.replace(uJs, '<u>$1</u>');
}
textarea {
width: 300px;
height: 80px;
resize: vertical;
}
<div class="block">
<textarea id="textarea" placeholder="Type here.."></textarea>
</div>
<div class="block">
<div class="textarea-preview"></div>
</div>
这篇关于JavaScript-更新< textarea>在特定条件下的值,并将其附加到< div>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!