如何使用 jquery/javascript 在 div 中获取选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5801347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:23:41  来源:igfitidea点击:

how to get selection inside a div using jquery/javascript

javascriptjquery

提问by ehsan

there are lots of code to get selection in a page, but i want a code to get selection inside a div, if the selection is outside of my div, the function must return empty string;

有很多代码可以在页面中获取选择,但我想要一个代码来获取 div 内的选择,如果选择在我的 div 之外,则该函数必须返回空字符串;

there is a jquery plugin that works only for textarea but not div. (here)

有一个 jquery 插件只适用于 textarea 但不适用于 div。(这里)

thanks

谢谢

回答by Tim Down

This is slightly verbose because of long-winded boundary comparisons and because IE takes a different approach from other browsers, but does the job in all major browsers. It also handles multiple selections in Firefox.

由于冗长的边界比较以及 IE 与其他浏览器采用不同的方法,这有点冗长,但在所有主要浏览器中都可以完成这项工作。它还处理 Firefox 中的多项选择。

jsFiddle: http://jsfiddle.net/Q982A/2/

jsFiddle:http: //jsfiddle.net/Q982A/2/

Code:

代码:

function getSelectedTextWithin(el) {
    var selectedText = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection(), rangeCount;
        if ( (rangeCount = sel.rangeCount) > 0 ) {
            var range = document.createRange();
            for (var i = 0, selRange; i < rangeCount; ++i) {
                range.selectNodeContents(el);
                selRange = sel.getRangeAt(i);
                if (selRange.compareBoundaryPoints(range.START_TO_END, range) == 1 && selRange.compareBoundaryPoints(range.END_TO_START, range) == -1) {
                    if (selRange.compareBoundaryPoints(range.START_TO_START, range) == 1) {
                        range.setStart(selRange.startContainer, selRange.startOffset);
                    }
                    if (selRange.compareBoundaryPoints(range.END_TO_END, range) == -1) {
                        range.setEnd(selRange.endContainer, selRange.endOffset);
                    }
                    selectedText += range.toString();
                }
            }
        }
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
        var selTextRange = document.selection.createRange();
        var textRange = selTextRange.duplicate();
        textRange.moveToElementText(el);
        if (selTextRange.compareEndPoints("EndToStart", textRange) == 1 && selTextRange.compareEndPoints("StartToEnd", textRange) == -1) {
            if (selTextRange.compareEndPoints("StartToStart", textRange) == 1) {
                textRange.setEndPoint("StartToStart", selTextRange);
            }
            if (selTextRange.compareEndPoints("EndToEnd", textRange) == -1) {
                textRange.setEndPoint("EndToEnd", selTextRange);
            }
            selectedText = textRange.text;
        }
    }
    return selectedText;
}

Alternatively, you could use my Rangylibrary, and the code becomes:

或者,您可以使用我的Rangy库,代码变为:

function getSelectedTextWithin(el) {
    var selectedText = "";
    var sel = rangy.getSelection(), rangeCount = sel.rangeCount;
    var range = rangy.createRange();
    range.selectNodeContents(el);
    for (var i = 0; i < rangeCount; ++i) {
        selectedText += sel.getRangeAt(i).intersection(range);
    }
    return selectedText;
}

回答by wong2

You can use:

您可以使用:

var node = window.getSelection ?        
       window.getSelection().focusNode.parentNode:
       document.selection.createRange().parentElement();

to get the element in which the selection end.

获取选择结束的元素。

Then you can determine if that element is inside your div.

然后您可以确定该元素是否在您的 div 内。

回答by Rory McCrossan

You can achieve this by using the Text select plugin - http://plugins.jquery.com/node/7411

您可以通过使用文本选择插件来实现这一点 - http://plugins.jquery.com/node/7411

In the binding code you can then interrogate the event target to see if it is within the element you require.

在绑定代码中,您可以询问事件目标以查看它是否在您需要的元素内。

<script type="text/javascript">
    $(function() {
        $(document).bind('textselect', function(e) {
            if ($(e.target).attr("id") == "myPara") {
                alert(e.text);
            }
        });   
    });
</script>

<p id="myPara">Lorem ipsum dolor sit amet consectetuer Lorem sapien hendrerit elit Cum. Morbi Curabitur convallis sagittis vitae sem parturient augue orci tortor eget. Et porttitor eros id consectetuer est molestie tellus fames netus nec. Ullamcorper id Nam eros sed nascetur Maecenas turpis at laoreet eleifend. Lorem id parturient dapibus Aenean cursus congue justo auctor pharetra orci. Hac amet.</p>

<p id="noSelect">Lorem ipsum dolor sit amet consectetuer Lorem sapien hendrerit elit Cum. Morbi Curabitur convallis sagittis vitae sem parturient augue orci tortor eget. Et porttitor eros id consectetuer est molestie tellus fames netus nec. Ullamcorper id Nam eros sed nascetur Maecenas turpis at laoreet eleifend. Lorem id parturient dapibus Aenean cursus congue justo auctor pharetra orci. Hac amet.</p>