2

快疯了...

我想知道用户是否选择了一个或多个元素。但是,这些元素应该只包括带有文本的实际元素。

我尝试将选择锚节点(开始)与选择焦点节点(结束)进行比较,并查看它们是否相同。但是,这会在不同的浏览器中给出不同的结果,并且会根据文本的选择方式产生不同的结果。这需要至少在 IE (> 8)、FireFox 和 Chrome 中工作。

在包含的 html 示例(和小提琴)中:

双击选择“三”:

Chrome:
   startNode: textNode containing "Three"
   endNode:   textNode containing "Three"

FireFox/IE:
   startNode: empty textNode (presumably between two and three)
   endNode:   textNode containing "Three"

通过单击并拖动选择“三”:

Chrome:
   startNode: textNode containing "Three"
   endNode:   textNode containing "Three"

FireFox/IE:
   startNode: textNode containing "Three"
   endNode:   textNode containing "Three"

双击“two”,选择它和它后面的空格:

Chrome:
   startNode: textNode containing "one two"
   endNode:   empty textNode

FireFox/IE:
   startNode: textNode containing "one two"
   endNode:   textNode containing "Three"

我想要的是让所有上述情况都意识到它实际上只有一个被选中的节点。我想规则是检查选择中的所有文本是否来自同一个节点。所以我试图遍历它,你瞧,nextSibling、children 等等对于不同的浏览器是不同的。

http://jsfiddle.net/SvNm8/

<!DOCTYPE html>
<html>

     <li>
       <span>one two</span> <span>three</span>
    </li>
    <div id = "x"></div>

</html>

<script> // to show results
document.onmouseup=function(){

    var userSelection = window.getSelection();
    var selected_element = userSelection.anchorNode;
    var last_selected_element = userSelection.focusNode;

    document.getElementById("x").innerHTML = selected_element.nodeName + " " + selected_element.nodeValue + " " + last_selected_element.nodeName + " " + last_selected_element.nodeValue ;

    };
</script>
4

0 回答 0