私は苦労してきました選択開始そして選択終了テキストエリアの属性を動作させるコンテンツ編集可能div 要素。Google や SO で関連記事をたくさんチェックしましたが、役に立ちませんでした。次のようなものがあり、textarea では完璧に機能しています。ただし、これを contenteditable div でも機能させたいです。
function replaceVal(node, val, step){
//...
var cursorLoc = node.selectionStart;
node.value = node.value.substring(0, node.selectionStart - step) + value +
node.value.substring(node.selectionEnd, node.value.length);
node.scrollTop = scrollTop;
node.selectionStart = cursorLoc + value.length - step;
node.selectionEnd = cursorLoc + value.length - step;
//...
}
これを変更して、textarea ではなく contenteditable div 要素で動作するようにするにはどうすればよいでしょうか?
ベストアンサー1
これを試してください。contentEditable かどうかに関係なく、選択されたテキストが返されます。
function GetSelectedText() {
if (document.getSelection) { // all browsers, except IE before version 9
var sel = document.getSelection();
// sel is a string in Firefox and Opera,
// and a selectionRange object in Google Chrome, Safari and IE from version 9
// the alert method displays the result of the toString method of the passed object
alert(sel);
}
else {
if (document.selection) { // Internet Explorer before version 9
var textRange = document.selection.createRange();
alert(textRange.text);
}
}
}
<div>Test Example Microsoft T-shirt box</div>
<button onClick="GetSelectedText()">Get text</button>
この例はjsfiddlerで作成しました。ここにリンクの説明を入力してください