4

我有一个包含许多表格和 div 的页面。其中一个带有一些文字。页面在此 div 之后还有一个 url。

需要: - 如果用户从 div id = "comment" 中选择文本(div 内的文本和另一个 div 内的文本进入此 div),则在按下 url 后仅收到此文本的警报(不带标签)。- 如果用户选择的文本不是来自 div(文本不在 div 内) - 什么也不做。

我已经尝试使用 CSS 使页面中的其他 DIV 和表格无法选择(-moz-user-select: -moz-none;-khtml-user-select: none;-webkit-user-select: none;-o-用户选择:无;用户选择:无;”但这不是我要搜索的方式...需要 javascript。

<html>
<head><title>1</title></head>
<body>
    <script type="text/javascript">

        function getSelectedval(){

            var txt = '';
            if (window.getSelection) {
                txt = window.getSelection();
            } else if (document.getSelection) {
                txt = document.getSelection();
            } else if (document.selection) {
                txt = document.selection.createRange().text;
            }
            alert(txt);
        }
    </script>

    <div>hello my friend</div>
    <br/>
    <div id="comment">here is just a some text for testing <div id="text"><strong>this div inside div</strong></div> this selected value</div>
    <a href="javascript:getSelectedval()">url</a>
</body>
</html>

谢谢

4

1 回答 1

3
function select() {

var flag = 0;
sel = window.getSelection();
for (var i = 0; i < sel.rangeCount; i++) {
    var s = sel.getRangeAt(i).startContainer.parentNode.id;
    var e = sel.getRangeAt(i).endContainer.parentNode.id;
    if (s == "a") flag = 1;
    if (flag = 1 && e == "a" || e == "child") flag = 2;
}

if (flag == 2) alert(sel);

}

document.getElementById("btn").addEventListener("click", function () {
select();
});

http://jsfiddle.net/gRYQR/2/

于 2013-08-30T09:40:25.733 回答