如何在javascript中使用Range对象检查选择的节点?

时间:2010-11-17 13:29:44

标签: javascript range

我想检索选择并检查选择的节点。我正在尝试使用代码。但我认为,我无法指出选择,因此代码失败了。

<head>
<script type="text/javascript">
    function SelectAnchorNode () {
        if (window.getSelection) {        // Firefox, Opera, Google Chrome and Safari
            var selection = window.getSelection ();
            if (selection.anchorNode) {
                var rangeToSelect = document.createRange ();
                alert(selection.anchorNode.nodeName);

        } else {
            alert ("Your browser does not support this example!");
        }
    }
</script>
</head>
<body>
    <button onclick="SelectAnchorNode ();">Click to check!</button>
    <br /><br />
    <div>
        <div>This is the first line.</div>
        <p>This is the second line.</p>
    </div>
</body>

1 个答案:

答案 0 :(得分:0)

您的代码中有一些错误,缺少“}”以关闭该功能。

此选项不会返回true,因为选择是在按钮上而不是在锚点(链接)上进行的

尝试使用此代码(我知道这不是您想要的,但它可以使您的示例正常工作)

<html>
<head>
<script type="text/javascript">
    function SelectAnchorNode () {
        if (window.getSelection) {        // Firefox, Opera, Google Chrome and Safari
            var selection = window.getSelection();
            if (selection.anchorNode) {
                var rangeToSelect = document.createRange();
                alert(selection.anchorNode.nodeName);
            } else {
                alert ("Your browser does not support this example!");
            }
        }
    }
</script>
</head>
<body>
<a onclick="SelectAnchorNode();">Click to check!</a>
<br /><br />
<div>
    <div>This is the first line.</div>
    <p>This is the second line.</p>
</div>

如您所见,我将“按钮”替换为“a”,并添加了缺少的“}”

EDIT!
请尝试使用此行,(我现在假设您希望获得用户的选择,并且您不想使用javascript创建选择?)

alert(selection.anchorNode.parentNode.nodeName);

根据您开始选择的位置,您将获得不同的结果,您还需要首先检查是否选择了文本节点(因为我可以直接在正文中进行选择)。但我希望这能让你更接近你的解决方案。

问候
托拜厄斯