编写一个在线文本编辑器

Coding an online text editor

本文关键字:在线 文本 文本编辑 编辑器 一个      更新时间:2023-09-26

我正在尝试使用html和javascript编写文本编辑器。我发现了下面的小提琴,我们可以在一个文本区域输入文本,点击预览按钮可以在它下面的区域看到预览。

我想摆脱预览区,并有文本粗体在同一文本区域,其中键入的文本。这是怎么做到的呢?

代码如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#my_textarea{
    width:300px;
    height:150px;
    border:thin solid #000;
    color:#000;
    padding:10px;
    min-height:150px;
    min-width:300px;
    max-height:150px;
    max-width:300px;
}
#preview{
    width:300px;
    height:150px;
    border:thin solid #000;
    color:#000;
    padding:10px;
    min-height:150px;
    min-width:300px;
    max-height:150px;
    max-width:300px;
}
</style>
<script type="text/javascript"> 
function formatText(tag) {
   var myTextArea = document.getElementById('my_textarea');
   var myTextAreaValue = myTextArea.value;
   var selected_txt = myTextAreaValue.substring(myTextArea.selectionStart, myTextArea.selectionEnd);
   var before_txt = myTextAreaValue.substring(0, myTextArea.selectionStart);
   var after_txt = myTextAreaValue.substring(myTextArea.selectionEnd, myTextAreaValue.length);
   myTextArea.value = before_txt + '<' + tag + '>' + selected_txt + '</' + tag + '>' + after_txt;
}
function preview() {
    var textbox , view ;
    textbox = document.getElementById('my_textarea');
    view = document.getElementById("preview");
    view.innerHTML = textbox.value
}
function onload(){
    var textarea = document.getElementById("my_textarea");
    textarea.onkeypress = function(e){
        if( e.which === 13)
        {
            this.value += "<br>";
        }
    }
}
</script>
</head>
<body onLoad="onload();">
<input type="button" value="bold" onClick="formatText ('b');" /> 
<input type="button" value="italic" onClick="formatText ('i');" /> 
<input type="button" value="underline" onClick="formatText ('u');" /><br><br>
<textarea name="my_textarea" id="my_textarea"></textarea><br><br>
<div id="preview"></div><br>
<button id="btn" onClick="preview();">Preview</button>
</body>
</html>

JS小提琴:http://jsfiddle.net/yZ6Va/

查看contenteditable的HTML属性:

<div contenteditable="true">
  This text can <b>be edited</b> by the user.
</div>

关于MDN的更多信息

保持js/视图

如果您的受众熟悉HTML,您可能希望使用JavaScript保留文本区以更新查看器。可编辑的<div>似乎是一个不错的功能,但它允许用户从Word文档中复制/粘贴,随之而来的是令人难以置信的MS标签负载,其中大部分是空的。谁想在数据库中查看这些文本的原始形式?

下面的编辑器给出

  • 更多标签帮助-带有快捷键的按钮-可能有价值,
  • 动态更新预览

,虽然没有遵循原始请求成为一个没有javascript的可编辑区域,但它节省了您的数据库(和您,如果您必须查看原始文本)

<script type="text/javascript" src="pathTo/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    updCont();//in case existing text
    var ht = window.innerHeight - $("#dvInput").css("height").replace(/[^.0-9]/g, '') - 30;
    if(ht<200) ht = 200;//display height minimum (may extend a bit below page)
    $("#dvCont").css("height", ht + "px");
    $("#txtCont").keydown(function(e){
        var curKey = e.which ? e.which : e.key;
        if(e.ctrlKey && e.shiftKey){
            if([56,190,80,65,83,76,85,79].indexOf(curKey)>-1)
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            if(curKey == 56) fmt("bull");// *
            else if(curKey == 190) fmt("indnt");// >
            else if(curKey == 80) fmt("para");// P
            else if(curKey == 65) fmt("href");// A
            else if(curKey == 83) fmt("spn");// S
            else if(curKey == 76) fmt("li");// L
            else if(curKey == 85) fmt("ul");// U
            else if(curKey == 79) fmt("ol");// O
        }else if(e.ctrlKey){
            if([66,73,13,85].indexOf(curKey)>-1)
                e.preventDefault ? e.preventDefault() : (e.returnValue = false);
            if(curKey == 66) fmt("bld");// B
            else if(curKey == 73) fmt("ital");// I
            else if(curKey == 85) fmt("uLine");// U
            else if(curKey == 13) fmt("crlf");// [enter]
        }
        updCont();
    });
//    $("#inp").keydown(function(e){alert(e.which)})
});
function updCont(){
    $("#dvCont").html($("#txtCont").val());//stuff the display div with textarea html text
}
function fmt(inAct){
    //common needs
    var oTxt = $("#txtCont");
    var s = oTxt[0].selectionStart;
    var e = oTxt[0].selectionEnd;
    var raVal = [oTxt.val().substring(0, s), oTxt.val().substring(s, e), oTxt.val().substring(e), s, e];
    var ofstStart = 0;
    var ofstEnd = 0;
    if(inAct=="bld"){
        oTxt.val(raVal[0] + "<b>" + raVal[1]  + "</b>" + raVal[2]);
        //if you don't want text selected, add raVal[1].length to ofstStart 
        ofstStart = 3;
        //uncomment to place cursor after closing tag (also unselect - set ofstStart to same point)
        //ofstEnd = 4;
    }else if(inAct=="ital"){
        oTxt.val(raVal[0] + "<i>" + raVal[1]  + "</i>" + raVal[2]);
        ofstStart = 3;
        //ofstEnd = 4;
    }else if(inAct=="uLine"){
        oTxt.val(raVal[0] + "<u>" + raVal[1]  + "</u>" + raVal[2]);
        ofstStart = 3;
        //ofstEnd = 4;
    }else if(inAct=="ul"){
        oTxt.val(raVal[0] + "<ul>" + raVal[1]  + "</ul>" + raVal[2]);
        ofstStart = 4;
        //ofstEnd = 5;
    }else if(inAct=="ol"){
        oTxt.val(raVal[0] + "<ol>" + raVal[1]  + "</ol>" + raVal[2]);
        ofstStart = 4;
        //ofstEnd = 5;
    }else if(inAct=="li"){
        oTxt.val(raVal[0] + "<li style=''>" + raVal[1]  + "</li>" + raVal[2]);
        ofstStart = 13;
        //ofstEnd = 5;
    }else if(inAct=="indnt"){
        oTxt.val(raVal[0] + "<div class='dnt'>" + raVal[1]  + "</div>" + raVal[2]);
        ofstStart = 17;
        //ofstEnd = 5;
    }else if(inAct=="bull"){
        oTxt.val(raVal[0] + "<br />&nbsp; &bull; " + raVal[1]  + raVal[2]);
        ofstStart = 20;
    }else if(inAct=="para"){
        oTxt.val(raVal[0] + "<p>" + raVal[1]  + "</p>" + raVal[2]);
        ofstStart = 3;
        //ofstEnd = 4;
    }else if(inAct=="href"){
        oTxt.val(raVal[0] + "<a href='' class='' title=''>" + raVal[1]  + "</a>" + raVal[2]);
        ofstStart = 29;
        //ofstEnd = 4;
    }else if(inAct=="spn"){
        oTxt.val(raVal[0] + "<span class='' style=''>" + raVal[1]  + "</span>" + raVal[2]);
        ofstStart = 24;
        //ofstEnd = 4;
    }else if(inAct=="crlf"){
        oTxt.val(raVal[0] + "<br />" + raVal[1]  + raVal[2]);
        ofstEnd = 5;
    }
    updCont();
    //put cursor at end of selected range (ignores start if no selected text)
    oTxt[0].selectionStart = s + ofstStart;
    oTxt[0].selectionEnd = s + ofstStart + raVal[1].length;
    oTxt[0].focus();
}
</script>
<style>
.dnt{margin-left:40px;}
.styleBtn{width:20px;margin:2px 10px;border:1px solid black;background-color:#EEE;float:left;text-align:center;}
</style>
</head><body>
<div id="dvInput">
<div style="border:1px solid black;border-radius:5px;background-color:silver;font-weight:bold;padding:2px 5px;float:left;">
    <div style="float:left;margin:2px 20px;">Text Input:</div>
    <span onclick="fmt('bld');" title="CTRL+B: Bold selected text">
        <div class="styleBtn"><b>B</b></div>
    </span>
    <span onclick="fmt('ital');" title="CTRL+I: Italicize selected text">
        <div class="styleBtn"><i>I</i></div>
    </span>
    <span onclick="fmt('uLine');" title="CTRL+U: Underline selected text">
        <div class="styleBtn"><u>U</u></div>
    </span>
    <span onclick="fmt('ul');" title="CTRL+Shift+U: List Group <ul> (unordered) around highlighted/selected text">
        <div class="styleBtn" style="height:19px;font-size:5.5pt;">
            •__<br>
            •__
        </div>
    </span>
    <span onclick="fmt('ol');" title="CTRL+Shift+O: Ord List Group <ol> (ordered) around highlighted/selected text">
        <div class="styleBtn" style="height:19px;font-size:5.5pt;padding-top:2px;">
            1__<br>
            2__
        </div>
    </span>
    <span onclick="fmt('li');" title="CTRL+Shift+L: List Item <li> around highlighted/selected text">
        <div class="styleBtn" style="width:30px;">&lt;&bull;></div>
    </span>
    <span onclick="fmt('indnt');" title="CTRL+Shift+>: <div> Indent a selected block of text'n(No remove shortcut.'nManually delete <div></div> to undo/outdent)">
        <div class="styleBtn">></div>
    </span>
    <span onclick="fmt('bull');" title="CTRL+Shift+*: Bullet (and new line)">
        <div class="styleBtn">&bull;</div>
    </span>
    <span onclick="fmt('para');" title="CTRL+Shift+P: Paragraph <p> around highlighted/selected text">
        <div class="styleBtn">&para;</div>
    </span>
    <span onclick="fmt('crlf');" title="CTRL+Enter: New Line <br>">
        <div class="styleBtn">&ldsh;</div>
    </span>
    <span onclick="fmt('href');" title="CTRL+Shift+A: <a href>">
        <div class="styleBtn" style="width:33px;">&lt;a></div>
    </span>
    <span onclick="fmt('spn');" title="CTRL+Shift+S: <span>">
        <div class="styleBtn" style="width:48px;">&lt;spn></div>
    </span>
<!-- <input id="inp" size="2">-enter char, get ascii number -->
</div>
<textarea id="txtCont" rows="10" style="width:100%;" name="myText"
>lorem ipsum dolor magnificum est labat et nobis pacem</textarea><br />
</div>
Display:
<div id="dvCont" style="border:1px solid black;border-radius:5px;overflow-y:auto;"></div>