获取 <p> 标签上选定的文本

sca*_*bie 4 javascript jquery text dom

使用jquery或纯javascript,有没有办法获取标签当前选定的文本<p>?我知道input.selectionStart,但它只存在于<input>.

小智 5

这是一个简单的解决方案。适用于 chrome、safari、FF 和 IE9+,但您必须在您可能想要支持的任何其他旧版浏览器上进行测试。http://jsfiddle.net/YEu3k/1/

<p id="pText">here is some text</p>

<script>
    document.getElementById('pText').onmouseup = function(){
        var sel = window.getSelection(), range;
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
            alert(range);
        }
    };
</script>
Run Code Online (Sandbox Code Playgroud)