简体   繁体   中英

Code breaks when highlighting at selectionStart equal to zero

When ever I highlight at what would be selectionStart = 0; this code does not execute. However, if I highlight one character in front of the first character in the textarea, the code works. Any ideas about getting this code to work if I highlight at the first character in the textarea?

        function fontBBCode(font){
        var textbox = document.getElementById('content');
        var textSelected;
        var fontTagOpen = "[font=";
        var fontTagClose = "[/font]";
        var stringBuilder;
        var sel;
        var startSelPos;
        var endSelPos;
        var len;

        if (document.selection){//IE
            textbox.focus();
            sel = document.selection.createRange();
            textSelected = sel.text;
        }
        else if (textbox.selectionStart){//Mozilla
            startSelPos = textbox.selectionStart;
            endSelPos = textbox.selectionEnd;
            textSelected = textbox.value.substring(startSelPos, endSelPos);
        }

        alert(textSelected.length);
        alert(textbox.value.length);

        if (textSelected){
            stringBuilder = fontTagOpen.concat(font);
            stringBuilder = stringBuilder.concat("]");
            stringBuilder = stringBuilder.concat(textSelected);
            stringBuilder = stringBuilder.concat(fontTagClose);
            if(document.selection)//IE
                sel.text = stringBuilder;
            else if(textbox.selectionStart){//Mozilla
                len = textbox.value.length;
                textbox.value = textbox.value.substring(0,startSelPos) + stringBuilder + textbox.value.substring(endSelPos,len);
            }
        }
        else{
            stringBuilder = fontTagOpen.concat(font);
            stringBuilder = stringBuilder.concat("]");
            stringBuilder = stringBuilder.concat(fontTagClose);
            textbox.value += stringBuilder;
        }
    }

It's because the first character is at index zero, which makes your if statement evaluate to false when document.selection/document.selectionStart is 0.

if (document.selection >= 0) { ... 

Should do the trick

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