Pregunta

I've poked around and read that there is no method to find the current line in a div contenteditable so I'm trying to write a script to best estimate the current line.

var curLine = 1;
var curColumn = 1;

$(".editable").onkeydown = function(e) {
    var keyCode = e.keyCode || e.which;

    switch( keyCode ) {
        case 13:
            console.log("Enter; on line: " + curLine);
            curLine++;
            break;

        case 8:
            if( /* current line has a text length of 0 */ ) {
                console.log("Previous line prepended; previous enter reversed; on line: " + curLine);
                do {
                    curLine--;
                } while( curLine > 0 );
            }
            // } else if( /* single digit removed */ ) {
                // console.log("Bit prepended");
            // }
            break;
    }
};          

So, as you can see, I have a few questions. This bit: if( /* current line has a text length of 0 */ ) I can't seem to be able to target the current line and see if its string length is 0. Also, my do...while statement doesn't work, as if I hit backspace on the first line over and over again, it goes into negative numbers (when it should just stay at 1 [> 0]). Any help would be greatly appreciated.

¿Fue útil?

Solución

This is working for me in Chrome. Will test in other browsers now:

$(".editable").on("keyup", function(keyCode){
    var linesCount = $(".editable div").length + 1;
    $("#linesCount").html(linesCount + " lines.");
    return linesCount;
});

For every line, the content editable div will create a new div child. If you count these divs, you get the total amount of lines.

http://jsfiddle.net/hescano/PypeD/

Edit: For FF this actually produces <br> tags. You could count those.

FF: http://jsfiddle.net/PypeD/1/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top