最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show custom menu on text selection - Stack Overflow

programmeradmin1浏览0评论

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.

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.

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.

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.

Share Improve this question asked Jul 29, 2014 at 15:06 SriharshaSriharsha 2,4431 gold badge17 silver badges21 bronze badges 2
  • 2 Have you taken a look at window.getSelection()? You could write your own listener for it, and the selectionchange event is supported on IE and Chrome/Safari (though not Firefox or Opera) – hotforfeature Commented Jul 29, 2014 at 15:09
  • for not supported browsers u can add selection check via setInterval (its bad for perfomance, but will fix) – El' Commented Jul 29, 2014 at 15:20
Add a comment  | 

1 Answer 1

Reset to default 20

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.

发布评论

评论列表(0)

  1. 暂无评论