代码之家  ›  专栏  ›  技术社区  ›  Kyle

javascript/jquery-如何获取用户用光标选择的元素?

  •  2
  • Kyle  · 技术社区  · 14 年前

    如果用户突出显示 <h1> 用他们的光标,我怎么得到它? <H1gt; 对象?或者如果他们在 <li> ,我怎么弄到的? <理工大学; ?

    4 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    8 年前

    你需要处理 window.getSelection() .

        2
  •  3
  •   simplyharsh    14 年前

    您可以将文档上的选择作为,

    dd = window.getSelection();
    desiredElement = dd.focusNode.parentNode; // h1 or li or other 
    desiredTag = desiredElement.tagName; // its tagname
    

    快乐编码。

        3
  •  0
  •   Reigel Gallarde    14 年前
    $('h1').click(function(){
       alert(this); // `this` is the <h1> object clicked.
    });
    

    我在你的问题中遗漏了一些棘手的部分吗?

        4
  •  0
  •   Community CDub    8 年前

    您可以在所有现代主流浏览器中获取所选内容的父元素,如下所示。记住,现在火狐默认允许多个选择;此代码只使用第一个。

    另见我的答案: How can I get the DOM element which contains the current selection?

    function getSelectionContainerElement() {
        var sel, el;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt) {
                if (sel.rangeCount) {
                    el = sel.getRangeAt(0).commonAncestorContainer;
                    return (el.nodeType == 3) ? el.parentNode : el;
                }
            } else {
                // This happens in old versions of Safari. A workaround
                // exists, if you need it
            }
        } else if (document.selection && document.selection.createRange) {
            return document.selection.createRange().parentElement();
        }
    }