我正在尝试为我正在处理的项目提供一个文本编辑器,当我从一个textarea中选择文本然后只需点击一个按钮就可以将文本环绕它时,我就会陷入困境。
实施例:
一旦点击选中文字,我会有一个按钮Insert -
select me
将成为-select me-
这是我当前的HTML(jsfiddle mirror):
<div class="container wrapper">
<form class="create post" method="post" action="action.php?a=createPost">
<h1>Create a Post</h1>
<input name="title" type="text" placeholder="Title" autocomplete="off" autofocus="autofocus" maxlength="100" required/>
<textarea name="introduction" placeholder="Introduction" maxlength="255"></textarea>
<ul class="options">
<li><p>Article Edits:</p></li>
<li>
<a class="fa fa-italic" trigger="italic">icon-placeholder</a>
</li>
</ul>
<textarea name="content" placeholder="Article" required="required"></textarea>
<input type="submit" value="Submit for Review" />
</form>
</div>
这是我目前的CSS:
form.create.post {
height:auto;
overflow:auto;
}
form.create.post > h1 {
font-weight:800;
font-size:46px;
letter-spacing:-5px;
text-transform:uppercase;
}
form.create.post > input,
form.create.post > textarea {
display:block;
margin:0 0 5px;
padding:5px 10px;
border:solid 1px #CCC;
border-radius:2px;
}
form.create.post > input[name=title] {
width:50%;
}
form.create.post > input[type=submit] {
width:25%;
background-image:linear-gradient(#F7F7F7,#E7E7E7);
}
form.create.post > textarea {
width:calc(100% - 22px);
}
form.create.post > textarea[name=content] {
height:300px;
}
/*-- text editor --*/
form.create.post > ul {
height:auto;
overflow:auto;
margin-bottom:5px;
list-style-type:none;
}
form.create.post > ul > li {
display:inline-block;
}
form.create.post > ul > li > p {
padding:5px;
}
form.create.post > ul > li > a {
display:block;
padding:5px;
cursor:pointer;
}
我不知道从哪里开始使用javascript。
答案 0 :(得分:1)
JSFiddle - http://jsfiddle.net/bp0cs3ts/10/
HTML
<div class="container wrapper">
<form class="create post" method="post" action="action.php?a=createPost">
<h1>Create a Post</h1>
<input name="title" type="text" placeholder="Title" autocomplete="off" autofocus="autofocus" maxlength="100" required/>
<textarea name="introduction" placeholder="Introduction" maxlength="255"></textarea>
<ul class="options">
<li><p>Article Edits:</p></li>
<li>
<a class="fa fa-italic" trigger="italic">icon-placeholder</a>
</li>
</ul>
<input type="button" value="Insert -" onclick="insert('-');" />
<textarea name="content" id="content" placeholder="Article" required="required"></textarea>
<input type="submit" value="Submit for Review" />
</form>
</div>
的Javascript
function insert(val) {
var editor = document.getElementById("content");
var editorHTML = editor.value;
var selectionStart = 0, selectionEnd = 0;
if (editor.selectionStart) selectionStart = editor.selectionStart;
if (editor.selectionEnd) selectionEnd = editor.selectionEnd;
if (selectionStart != selectionEnd) {
var editorCharArray = editorHTML.split("");
editorCharArray.splice(selectionEnd, 0, val);
editorCharArray.splice(selectionStart, 0, val); //must do End first
editorHTML = editorCharArray.join("");
editor.value = editorHTML;
}
}