在文本选择上显示自定义菜单 [英] Show custom menu on text selection

查看:174
本文介绍了在文本选择上显示自定义菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我希望能够在用户选择与介质相似的文本时显示自定义菜单(或上下文菜单)。

Hi I want to have a ability to show the custom menu (or context menu) when a user selects some text much simillar to what medium provides.

如何实现这样的事情?我知道native / jquery上下文菜单插件,但我怎么知道用户何时选择文本? 浏览器的 onselect 似乎仅支持输入元素。

How do implement this something like this? I am aware of native/jquery context menu plugins, but how do I know when the user selects the text? Browser's onselect seems to be supported only on input elements.

推荐答案

这是 .getSelection()的一个非常基本的监听器: DEMO

Here is a pretty basic listener for .getSelection(): DEMO

if (!window.x) {
    x = {};
}

x.Selector = {};
x.Selector.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
}

$(document).ready(function() {
    $(document).bind("mouseup", function() {
        var selectedText = x.Selector.getSelected();
        if(selectedText != ''){
            alert(selectedText);
        }
    });
});

只需让您的弹出窗口/工具栏可见即可取代警报。希望这会有所帮助!

Instead of an alert, simply make your popup/toolbar visible. Hope this helps!

编辑
我更改了演示,以显示一种显示弹出菜单/工具栏的方法。

EDIT I changed the demo to show one possible way to show the popup menu/toolbar.

这篇关于在文本选择上显示自定义菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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