سؤال

I'm trying to append an <a> tag in to selected text when user right click on it.i searched over the stack , no matches found.

هل كانت مفيدة؟

المحلول

Dealing with selected text reliably is a bit tricky cross-browser. Tim Down's library Rangy can be useful there, he's smoothed over a lot of the browser idiosyncrasies. (Even if you don't want to use the library, you can study it for the techniques.)

One of the core Rangy demos is surrounding selected text with an element, using the RangyRange#surroundContents method. The code for that in the demo looks like this:

function getFirstRange() {
    var sel = rangy.getSelection();
    return sel.rangeCount ? sel.getRangeAt(0) : null;
}
function surroundRange() {
    var range = getFirstRange();
    if (range) {
        var el = document.createElement("span");
        el.style.backgroundColor = "pink";
        try {
            range.surroundContents(el);
        } catch(ex) {
            if ((ex instanceof rangy.RangeException || Object.prototype.toString.call(ex) == "[object RangeException]") && ex.code == 1) {
                alert("Unable to surround range because range partially selects a non-text node. See DOM Level 2 Range spec for more information.\n\n" + ex);
            } else {
                alert("Unexpected errror: " + ex);
            }
        }
    }
}

You'd be doing much the same, but with an a rather than a span.

نصائح أخرى

EDIT Noticed you were talking about selected text a little too late.

Maybe you could check document.elementFromPoint, only supported in FireFox I think.

Are you looking for something like this:

Html:

<div id="rightclick">
Right Click me:   
</div>​

Javascript:

$("#rightclick").mousedown(function(e) {
    if (e.which === 3) {
        $(this).append("<a href='http://www.google.com'>Link</a>");
    }
});
​

See the demo: http://jsfiddle.net/BgW7x/2/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top