在用户选择旁边显示菜单

时间:2018-09-12 09:21:51

标签: javascript selection

我有一种情况:

  1. 突出显示文本时,菜单/弹出窗口应显示
  2. 菜单应在用户光标右边显示5个像素,在用户光标下方显示5个像素

虽然我能够达到第一个,但定位菜单给我带来了困难。我尝试使用event.pageXevent.pageY解决它,但它仅在某些情况下有效

这是我的代码

      $(frameBody).on('mouseup', function (event) {
            var frame = $("#" + activeId).find('.vIframe')[0];
            var selection = $(frame)[0].contentWindow.getSelection();
            var exportMenu = $("#exportMenu") ;
            range = selection.getRangeAt(0);
            var boundary = event.target.getBoundingClientRect();
            var offset = $(frame).offset();
            if (selection.toString().trim().length > 0) {
                $(exportMenu).css('display', 'inline-block');
                $(exportMenu).menu('open');
                $(exportMenu).css({
                    'left': event.pageX + offset.left + $(exportMenu).width()/2 + 5,
                    'top': boundary.top + $(exportMenu).height() + 5
                });
                if ($($(frame)[0].contentWindow).height() < parseInt($(exportMenu).css('top'))) {
                    $(exportMenu).css({
                        'left': event.pageX,
                        'top': event.pageY - 5
                    });
                }
            } else {
                $(exportMenu).css('display', 'none');
            }
            event.stopPropagation();
        });

任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

这就是我最终解决这个问题的方式。

  $(frameBody).on('mouseup', function (event) {
        var activeId = TabManager.getActiveId();
        var frame = $("#" + activeId).find('.viewerIframe')[0];
        var selection = $(frame)[0].contentWindow.getSelection();
        var exportMenu = $("#" + TabManager.getActiveId()).find("#exportMenu")[0];
        range = selection.getRangeAt(0);
        var zoomfactor = $(frame).attr("zoom");
        selectionNode = $(frame)[0].contentDocument.createElement("highlights-start")
        if (selection.toString().trim().length > 0) {
            var range = selection.getRangeAt(0);
            newRange = document.createRange();
            newRange.setStart(selection.focusNode, range.endOffset);
            newRange.insertNode(selectionNode );
            $(exportMenu).css('display', 'inline-block');
            $(exportMenu).menu('open');
            $(exportMenu).css({
                'top': $(selectionNode).offset().top + $(exportMenu).height() / 2 - 20 + 'px',
                'left': $(selectionNode).offset().left+ 'px'
            });
           else {
            $(exportMenu).css('display', 'none');
        }
        event.stopPropagation();

    });