プログラミング部門のコードビットを節約するための小さなプロジェクトでは、CodeMirrorを使用して構文の強調表示を行います。 asp-mvcページは、textxt、言語のドロップダウンリスト、説明のテキストボックス、およびコードのテキストボックスで構成されています。 ユーザーがドロップダウンから最初に選択すると、素敵なCodemirrorエディタが作成されます。言語選択を変更する場合は、新しいCodeMirrorボックスが作成され、最初のボックスの上にあらかじめ表示されます。これは選択が行われるたびに行われ、ボックスをスタックして混乱させます。 1つのCodemirrorエディタが常に好きです。たとえば、テキストを入力して言語を選択する場合、テキストを新しいCodeMirrorエディタにコピーするだけです。ここ はmanualでこれを行う方法の説明である:あなたが要素にエディタを追加したい、それが挿入されている方法をより詳細に制御する必要がない場合には言語ドロップダウンが選択されたときにCodeMirrorが追加され続ける
、最初の引数CodeMirror関数への は、 DOM要素が与えられたときに、その要素をドキュメントのどこかに挿入する関数にすることもできます。これがために使用 、例えば、実際のエディタでテキストエリアを置き換えることができ:
VAR myCodeMirror = CodeMirror(関数(ELT){
myTextArea.parentNode.replaceChild(ELT、myTextArea);}、{値: myTextArea.value});しかし、この使用例では、CodeMirrorを使用する一般的な方法である を使用すると、ライブラリはより強力なショートカットを提供します。var myCodeMirror = CodeMirror.fromTextArea(myTextArea);これは、 のフォームが(フォームの一部である場合)である場合、 のうち、テキストエリアの値が のエディタの内容で更新されるようにします。
私のコードでわかるように、私は2番目の方法を使用していますが、役に立たないものです。相続人は、マークアップとJavaScript:
@using (Html.BeginForm("Save", "Home", FormMethod.Post, new {id="CodeBlock"}))
{
@Html.TextBoxFor(m => m.Title, new { type = "Search", autofocus = "true", id = "title", placeholder = "Code snip Title", style = "width: 200px", @maxlength = "50" })
@Html.DropDownList("Language",
new SelectList(Enum.GetValues(typeof(LangType))),
"Select Language", new {id="codeDDl", @onchange = "changeSyntax()" })
<p></p>
@Html.TextAreaFor(m => m.Description, new { type = "Search", autofocus = "true", id = "description", placeholder = "Code snip Description",style = "Width: 800px" })
<p></p>
<div id="CodeArea">
@Html.TextAreaFor(m => m.Code, new {id = "code", style = "width: 800px"})
</div>
<p></p>
<input type="submit" value="Submit" />
<input type="button" value="Reset" onclick="Reset()"/>
}
<script>
var cm;
function changeSyntax() {
switch (document.getElementById("codeDDl").selectedIndex) {
case 1:
BuildBox(true, true, "text/x-csharp");
break;
case 2:
BuildBox(true, true, "text/x-css");
break;
case 3:
BuildBox(true, true, "text/x-chtml");
break;
case 4:
BuildBox(true, true, "text/x-javascript");
break;
case 5:
BuildBox(true, true, "text/x-perl");
break;
case 6:
BuildBox(true, true, "text/x-php");
break;
case 7:
BuildBox(true, true, "text/x-python");
break;
case 8:
BuildBox(true, true, "text/x-ruby");
break;
case 9:
BuildBox(true, true, "text/x-sql");
break;
case 10:
BuildBox(true, true, "text/x-vb");
break;
case 11:
BuildBox(true, true, "text/x-xml");
break;
}
}
function BuildBox(lines, match, mode) {
cm = CodeMirror.fromTextArea(document.getElementById("code"),
{
lineNumbers: lines,
matchBrackets: match,
mode: mode
});
}
function Reset() {
cm.toTextArea();
document.getElementById("code").value = "";
document.getElementById("codeDDl").disabled = false;
document.getElementById("codeDDl").selectedIndex = 0;
}
モデルはシンプルで、カミソリのコントロールから派生することができ、コントローラは、この時点では特別何もしません。 言語選択ボックスが何回変更されても、CodeMirror Editorを1つしか使用できないというアイデアはありますか?