简体   繁体   中英

How can I replace hash tag on keydown event like twitter or facebook. javascript // jquery

I have contentEditable element(maybe div...) and I would like to replace hash tag or url like twitter(or facebook) on keydown event.

I can normally archieve it with this below..

    //onKeydown Event
    ....

    _this.saveRange();   // save current range

    var string = _this.getHtml();    //_this is contentEditable element (div)

    var reg = /(:?#{1}|\s#{1})([A-Za-z0-9.;_\-ㄱ-ㅎ|ㅏ-ㅣ|가-힣]+)/gm;

    if(reg.test(string)) {
        var text = string.replace(reg, function(u) {
            return '<a class="highlight" rel="external" id="test">' + u + '</a>';
        });

        _this.setHtml(text);    // insert html what replaced using innerHtml 

        _this.restoreRange();

    }

This works fine replace text.. on keydown event.

But when I set html that replaced, document range(cursor) is move first position.

this is problem.

I saved range before innerHtml and restore range after innerHtml. But it doesn't work.

Below that I used function saveRange and restoreRange.

    var savedRange;   //public variable

    function saveRange() {
        if(window.getSelection) {
            savedRange = window.getSelection().getRangeAt(0);
        } else if(document.selection) {  //IE
            savedRange = document.selection.createRange();
        }
    }    



     function restoreRange() {
            if (savedRange != null) {
                    if (window.getSelection)//non IE and there is already a selection
                    {
                        var s = window.getSelection();
                        if (s.rangeCount > 0) 
                            s.removeAllRanges();
                        s.addRange(savedRange);
                    }
                    else if (document.createRange)//non IE and no selection
                    {
                        window.getSelection().addRange(savedRange);
                    }
                    else if (document.selection)//IE
                    {
                        savedRange.select();
                    }
                }
         }

Can anybody come up with solution to this ??? or give me a link.....

You could save and restore the selection range by character index so long as the text content is remaining the same. I've provided simple functions to do this here:

https://stackoverflow.com/a/17694760/96100

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