jquery:选择文本事件 [英] jquery: select text event

查看:89
本文介绍了jquery:选择文本事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户选择一些文本(非文本区域或输入)时,jquery可以调用我的回调让我知道选择了哪个div的文本,如果选择的焦点丢失也可以调用我的回调?

is it possible that when user selected some text(non textarea nor input), jquery can call my callback to let me know which div's text is selected, and if the select focus is lost also call my callback?

谢谢。

推荐答案

有些令人惊讶的是,没有简单的方法可以做到这一点。 IE有一个实施的选择活动所有元素,但其他浏览器从未扩展到输入之外。您必须在整个文档中处理 keyup mouseup 事件,即便如此,您的回调可能也是如此当选择没有实际改变时调用。

Somewhat surprisingly, there's no simple way to do this. IE has a select event that is implemented on all elements but other browsers have never extended this beyond inputs. You'll have to handle keyup and mouseup events on the whole document, and even then, your callback may well be called when the selection hasn't actually changed.

更新2013年10月13日

WebKit浏览器支持 Document 节点上的 selectionchange 事件许多年。 IE也支持此事件回到5.5版。示例:

WebKit browsers have supported the selectionchange event on Document nodes for a couple of years. IE also supports this event back to version 5.5. Example:

document.onselectionchange = function() {
    console.log("Selection changed");
};






这是一个简单的例子:


Here's a simple example:

function selectCallback(selectionParentElement) {
    console.log("Selecting, parent element is " + selectionParentElement.nodeName);
}

var mouseOrKeyUpHandler;

if (typeof window.getSelection != "undefined") {
    // Non-IE
    mouseOrKeyUpHandler = function() {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            if (range.toString()) {
                var selParentEl = range.commonAncestorContainer;
                if (selParentEl.nodeType == 3) {
                    selParentEl = selParentEl.parentNode;
                }
                selectCallback(selParentEl);
            }
        }
    };
} else if (typeof document.selection != "undefined") {
    // IE
    mouseOrKeyUpHandler = function() {
        var sel = document.selection;
        if (sel.type == "Text") {
            var textRange = sel.createRange();
            if (textRange.text != "") {
                selectCallback(textRange.parentElement());
            }
        }
    };
}

document.onmouseup = mouseOrKeyUpHandler;
document.onkeyup = mouseOrKeyUpHandler;

这篇关于jquery:选择文本事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆