记录选定的文本位置,给出错误的结果

Document selected text position giving wrong result

本文关键字:出错 错误 结果 位置 文本 记录      更新时间:2023-09-26

一旦用户选择了一些文本,我就会尝试显示工具提示。 客户端选择文本后,我将弹出窗口放在所选文本附近,为此我使用此功能,它我弄错了xy位置.. 有什么帮助吗?

$(document).ready(function(){
    $('.document').click(function(e) {
        if(getSelectedText()  !="") { //checking user selected some text?
            var x = e.pageX;
            var y = e.pageY;
               $(".savetooltipAll").css("top",y); //wrong not near to text selection
               $(".savetooltipAll").css("left",x); //wong not near to text selection
               $(".savetooltipAll").show();
        } else {
            $(".savetooltipAll").hide();
        }
    })
});

很快做了一个版本。需要更改/优化定位以适应您的 HTML 代码和需求。

杰斯菲德尔:http://jsfiddle.net/j5jzaa5e/

$(document).ready(function(){
    $('body').mouseup(function(e) {
        // Get the selection range
        var range = window.getSelection().getRangeAt(0);
        // Check if text was actually selected
        if (!range.collapsed) {
            // Get bounds & set tooltip pos
            var bounds = range.getBoundingClientRect();
            var x = bounds.left + ((bounds.right - bounds.left - $(".savetooltipAll").outerWidth()) / 2);
            var y = bounds.top - $(".savetooltipAll").outerHeight() + $(window).scrollTop();
            $(".savetooltipAll").css("top", y + 'px');
            $(".savetooltipAll").css("left",x + 'px');
            $(".savetooltipAll").show();
        } else {
            $(".savetooltipAll").hide();
        }
    })
});

检查 2 件事:

您必须定义工具提示在 css 文件中的位置。

.savetooltipAll {
    position: absolute;
}

savetooltipAll的元素应该是主体的直接子元素(以避免位置上下文):

<body>
    <div class="savetooltipAll"></div>
    <ul>
        <li class="document">
        </li>
        <li class="document">
        </li>
相关文章: