Wrap certain word with using jquery

后端 未结 2 863
既然无缘
既然无缘 2021-01-13 00:36

I have the following div:

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 01:15

    I did a proof of concept with some modifications from what you originally had. See below,

    DEMO: http://jsfiddle.net/cgy69/

    $(function() {
        $('div').focus();
        var x = ['SELECT', 'WHERE', 'FROM'];
        $('div').keyup(function(e) {
            //console.log(e.keyCode) ;
            if (e.keyCode == 32) {
    
                //using .text() remove prev span inserts
                var text = $.trim($(this).text()).split(' ');            
                $.each(text, function(i, v) {
                    $.each(x, function(j, xv) {
                        if (v.toUpperCase() === xv) {
                            text[i] = '' + v + '';    
                        }                                        
                    });
                });
    
                $(this).html(text.join(' ') + ' ');
    
                setEndOfContenteditable(this);
            }
        });
    
        function setEndOfContenteditable(contentEditableElement) {
            var range, selection;
            if (document.createRange) //Firefox, Chrome, Opera, Safari, IE 9+
            {
                range = document.createRange(); //Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement); //Select the entire contents of the element with the range
                range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection(); //get the selection object (allows you to change selection)
                selection.removeAllRanges(); //remove any selections already made
                selection.addRange(range); //make the range you have just created the visible selection
            }
            else if (document.selection) //IE 8 and lower
            {
                range = document.body.createTextRange(); //Create a range (a range is a like the selection but invisible)
                range.moveToElementText(contentEditableElement); //Select the entire contents of the element with the range
                range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
                range.select(); //Select the range (make it the visible selection
            }
        }
    });
    

    You going to extend this further to handle

    1. Backspace
    2. HTML contents from previous inserts
    3. Cursor position Partially done, editing in the middle would still mess up the caret.

    and more..

提交回复
热议问题