简体   繁体   中英

How can I show an object at the location where I select text?

I want to create a CMS like wordpress. In my text editor I want the user to be able to create a hyperlink via a button click. But I don't want to show an alert so the user can input the url but a div shown under the selected word/sentence inside or over the text area with an text input. How do I get the location of the selected word?

I already tried to append a textnode to it like this:

window.getSelection().appendChild(document.createTextNode("testing"));

but I get an error, that .appendChild() is not a function.

$('#btnLink').click(function() {
   window.getSelection().appendChild(document.createTextNode("testing"));
})

I expect the textnode is appended to the selected word, but it doesnt work

try this:

$('#btnLink').click(function() {
   window.getSelection.append(document.createTextNode('testing'));
})

.appendchild() is a javascript function, jquery can't use it. use .append() instead and use .createTextNode() inside it.

The getSelection() method will not return a node to append text to.

I've used some code from a different answer (added below the code) to achieve what you're asking.

$('#btnLink').click(function() {
    var elm = getRange();
    var div = document.createElement("div");
    div.appendChild( document.createElement("input") );
    elm.collapse(false);
    elm.insertNode(div);
});

function getRange() {
    var range, sel, container;
    if (document.selection) {
        range = document.selection.createRange();
        range.collapse(isStart);
        return range.parentElement();
    } else {
        sel = window.getSelection();
        if (sel.getRangeAt) {
            if (sel.rangeCount > 0) {
                range = sel.getRangeAt(0);
            }
        } else {
            // Old WebKit
            range = document.createRange();
            range.setStart(sel.anchorNode, sel.anchorOffset);
            range.setEnd(sel.focusNode, sel.focusOffset);

            // Handle the case when the selection was selected backwards (from the end to the start in the document)
            if (range.collapsed !== sel.isCollapsed) {
                range.setStart(sel.focusNode, sel.focusOffset);
                range.setEnd(sel.anchorNode, sel.anchorOffset);
            }
       }

        if (range) {
           return range;
        }   
    }
}

This code is copied and altered from How can I get the DOM element which contains the current selection? to demonstrate the use for this specific question.

A JSFiddle: https://jsfiddle.net/zuvq9nyc/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM