31

textarea のselectionStart属性とselectionEnd属性をcontenteditable div 要素で機能させるのに苦労しています。私はグーグルとSOで多くの関連記事をチェックしましたが、役に立ちませんでした。テキストエリアで完全に機能する次のようなものがあります。しかし、これを 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 要素で動作するように、これをどのように変更できますか?

4

3 に答える 3

12

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で作成します。 ここにリンクの説明を入力してください

于 2015-11-11T18:09:41.530 に答える