コンテンツを編集可能な<UL>のばかげた証拠にするために、次のキーアップ/ダウンハンドラーを作成しました。*
それは2つのことをします:
- <UL>が空の場合、<LI>を<UL>に追加します。SO(Tim Downから)で見つけたコードを使用して、予想される場所にキャレットを配置します
- すべての非LI/非BRタグをクリーンアップします。これは基本的に、手っ取り早いペーストクリーナーです。
これは、jqueryとDOM操作の快適さのレベルを押し上げているので、おそらく私がもっとうまくできることがいくつかありますが、それはそのままでかなりうまく機能します。
//keyup prevented the user from deleting the bullet (by adding one back right after delete), but didn't add in li's on empty ul's, thus keydown added to check
$('ul').on('keyup keydown', function() {
var $this = $(this);
if (! $this.html()) {
var $li = $('<li></li>');
var sel = window.getSelection();
var range = sel.getRangeAt(0);
range.collapse(false);
range.insertNode($li.get(0));
range = range.cloneRange();
range.selectNodeContents($li.get(0));
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
} else {
//are there any tags that AREN'T LIs?
//this should only occur on a paste
var $nonLI = $this.find(':not(li, br)');
if ($nonLI.length) {
$this.contents().replaceWith(function() {
//we create a fake div, add the text, then get the html in order to strip out html code. we then clean up a bit by replacing nbsp's with real spaces
return '<li>' + $('<div />').text($(this).text()).html().replace(/ /g, ' ') + '</li>';
});
//we could make this better by putting the caret at the end of the last LI, or something similar
}
}
});
http://jsfiddle.net/aVuEk/5/のjsfiddle
*私は、トレーニングがすべての場合において最良/最も簡単な解決策であるという、Diodeusに敬意を表して同意しません。私の状況では、ページ上にコンテンツ編集可能な<UL>がいくつかあります。これらは非常にインラインのWYSIWYGであり(つまり、tinymceスタイルのクロムの余地はあまりありません)、カジュアルで初めての上級者以外のユーザーが使用します。