![](/img/trans.png)
[英]Need to make selected text as bold/italic/underline using javascript, or need very basic text editors suggestions
[英]How to make selected text bold/italic/underlined in javascript?
我正在嘗試在允許用戶為學校項目編寫自己的筆記的網頁上工作,我的想法是讓他們使用按鈕粗體/斜體/突出顯示他們的文本。 截至目前,按鈕正在工作,但它們粗體/斜體/突出顯示文本區域內的所有內容。 相反,我希望它以這樣的方式工作,即只有它們突出顯示的文本才會變為粗體/斜體/下划線。 我也想知道如何制作它,以便當他們點擊粗體按鈕時,他們從那時開始輸入的文字將變為粗體,當他們再次點擊它時,從那時開始輸入的文本將會出現正常。
<script type="text/javascript">
function boldText(){
var target = document.getElementById("TextArea");
if( target.style.fontWeight == "bolder" ) {
target.style.fontWeight = "normal";
} else {
target.style.fontWeight = "bolder";
}
}
function italicText(){
var target = document.getElementById("TextArea");
if( target.style.fontStyle == "italic" ) {
target.style.fontStyle = "normal";
} else {
target.style.fontStyle = "italic";
}
}
function underlineText(){
var target = document.getElementById("TextArea");
if( target.style.textDecoration == "underline" ) {
target.style.textDecoration = "none";
} else {
target.style.textDecoration = "underline";
}
}
</script>
您可以使用execCommand()
。 此API用於開發文本編輯器。 3個按鈕使用非常通用的execCommand()
,而write元素是一個普通的div,具有屬性contenteditable
。
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <style> body { font: 400 16px/1.4 'serif'; } #editor1 { border: 3px inset grey; height: 100px; width: 381px; margin: 10px auto 0; } fieldset { margin: 2px auto 15px; width: 358px; } button { width: 5ex; text-align: center; padding: 1px 3px; } </style> </head> <body> <div id="editor1" contenteditable="true"> The quick brown fox jumped over the lazy dog. </div> <fieldset> <button class="fontStyle" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"><i>I</i> </button> <button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b> </button> <button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u> </button> </fieldset>
Textarea不允許這樣的事情。 我建議你使用像ckeditor這樣的東西 。 它會整齊地為你完成這項工作。 但是如果你仍然想自己做,你需要使用帶有contenteditable標簽的div
。
祝好運 !
使用textarea
你無法實現,改為使用divs
,所以你可以這樣做:
$(document).ready(function(){ $('.boldText').click(function(){ $('.container').toggleClass("bold"); }); $('.italicText').click(function(){ $('.container').toggleClass("italic"); }); $('.underlineText').click(function(){ $('.container').toggleClass("underline"); }); });
div.container { width: 300px; height: 100px; border: 1px solid #ccc; padding: 5px; } .bold{ font-weight:bold; } .italic{ font-style :italic; } .underline{ text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="container" contentEditable></div><br/> <input type="button" class="boldText" value="Bold"> <input type="button" class="italicText" value="Italic"> <input type="button" class="underlineText" value="Underline">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.