私のフォームでは、ユーザーがテキストをフォーマットしたり、リストなどを追加したりできるようにしたい(htmlを知らなくても基本的なhtml機能)。
例として太字ボタンを使用する:
<div class="goBold button">B</div>
<input type="text" name="txtMessage" />
<script>
$(".goBold").click(function() {
formatText("bold");
});
function formatText(formatType)
{
var input = $("#txtMessage");
var text = input.val();
var ss = input[0].selectionStart;
var se = input[0].selectionEnd;
if (formatType == "bold")
{
if (ss == se)
{
// there's no text in the textbox, so just write in the tags
input.val(text + "[b][/b]");
}
else
{
// surround the highlighted text with the tags
input.val(text.substr(0, ss) + "[b]" + text.substr(ss, se) + "[/b]" + text.substring(se, text.length));
}
}
}
</script>
これはすべて機能しますが、わずかな問題があります。
このテキストボックスのテキスト値が
速い赤いキツネは怠惰な茶色の犬を飛び越えます。これは、アルファベットの26文字すべてを使用する英語の唯一の文です
単語all 26 letters
が強調表示された状態で、太字のボタンをクリックすると、タグ内のテキストが折り返されますが、選択後に存在するテキストの2番目のコピーも追加されます。
これがなぜなのかわかりませんが、誰かがここで何か洞察を提供できますか?
TIA :)