开发者

How can I select the letter beside a text cursor with Javascript or jQuery?

I'm using jQuery and Lettering.js to wrap each letter in an <h1> with a span and give it a unique ID. I've also set contenteditable=true on the <h1> so when I click on it I can edit the text. How would I select the <span> element that is either to the left or right of the cursor, so I could apply styling to it?

Here's my code

<head>

    <style media="screen" type="text/css">
        body {text-align: center}
    </style>

    <script src="scripts/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="scripts/lettering.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
             $("h1").lett开发者_如何学Cering();
         });
    </script>

</head>

<body>

<h1 contenteditable="true" >Click me!</h1>

</body>

Would really appreciate any help or advice!


The following will work in all major browsers:

function getCaretContainerElement() {
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = sel.getRangeAt(0).commonAncestorContainer;
            return container.nodeType == 1 ? container : container.parentNode;
        }
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        return document.selection.createRange().parentElement();
    }
    return null;
}

var h1 = document.getElementById("foo");

h1.onkeyup = h1.onmouseup = function() {
    var caretContainerEl = getCaretContainerElement();
    if (caretContainerEl) {
        // Do stuff here
        alert(caretContainerEl.id);
    }
};

Here's a live example: http://jsfiddle.net/BATGH/1/


Adding a click event to each of the paragraph tags created by the lettering script will give you the element that was clicked on. Then you can use either prev or next method to get the letter before or after the letter that was clicked.

$(document).ready(function(){
    $("h1 p").click(function(){
        alert($(this).prev().html());
    });
});

I worked up an example that will show an alert with the previous letter. http://jsfiddle.net/5n5vJ/


Here's another library called Rangy which could work for you. Check out the additional module CSSClassApplierModule. It lets you wrap a selection in a class for styling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜