contenteditable元素中的selectionStart和selectionEnd [英] selectionStart and selectionEnd in contenteditable element

查看:194
本文介绍了contenteditable元素中的selectionStart和selectionEnd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力尝试textarea的 selectionStart selectionEnd 属性,以使其与 contenteditable div元素一起使用.我已经在Google和SO上检查了很多相关文章,但无济于事.我有一些类似于以下内容,可以完美地用于textarea.但是我希望这个可以与contenteditable div一起使用.

I have been struggling the selectionStart and selectionEnd attributes of textarea to make them work with contenteditable div element. I have checked a lot of related articles on google and on SO but to no avail. I have something similar to the following which is working for textarea perfectly. But I want this one to work with 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;
  //...
}

如何对其进行修改,使其可与可编辑内容的div元素(而不是textarea)一起使用?

How can this be modified so that it will work with contenteditable div element instead of textarea?

推荐答案

尝试此操作,无论是否为contentEditable,它都会返回选定的文本.

Try this, it returns the selected text, no matter if it's contentEditable or not.

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中创建了这个示例,看到了 在此处输入链接描述

I make this example in jsfiddler, see that enter link description here

这篇关于contenteditable元素中的selectionStart和selectionEnd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆