将元素定位到所选范围的中心

时间:2015-07-22 09:30:54

标签: javascript jquery html css

请在继续之前访问此link

选择文档上的文字,在第二次尝试上,您应该能够生成一个带有文本 test 的按钮。

现在我想要实现的是在文档上所选范围的顶部中心处生成元素。例如,请参阅下面的屏幕截图:

Desired solution.

当前的JS代码:

var position = '';
function getSelectedTextPos(){
    if(window.getSelection){
        var selection = window.getSelection();
        var range = selection.getRangeAt(0);
        var rect = range.getBoundingClientRect();
        return rect;
    }
    else if(document.getSelection){
        var selection = document.getSelection();
        var range = selection.getRangeAt(0);
        var rect = range.getBoundingClientRect();
        return rect;
    }
    else if(document.selection){
        var selection = document.selection.createRange();
        var range = selection.getRangeAt(0);
        var rect = range.getBoundingClientRect();
        return rect;
    }
}
$(document).on('mouseup', function (e) {
    position = getSelectedTextPos();
    console.log(position);
});

$("button").click(function (e) {
    console.log("Hello");
});

var selectedText = '';
function getSelectedText(){
    if(window.getSelection){
        return window.getSelection().toString();
    }
    else if(document.getSelection){
        return document.getSelection();
    }
    else if(document.selection){
        return document.selection.createRange().text;
    }
}

function checkSelectionChanged() {
    var current = getSelectedText();
    console.log(current);
    if(current != selectedText) {
        selectedText = current;
        if(selectedText != '') {
            $('#quote').offset(position);
            $('#quote').show();
        } else {
            $('#quote').hide();
        }
    }
}

setInterval(checkSelectionChanged, 250);

我尝试了各种排列和组合来实现它,但无济于事。

它在Chrome上的运作方式:

Working on Chrome

它如何在FireFox上运行:

Working on FireFox

0 个答案:

没有答案