3
4

1 に答える 1

6

You can't style only some parts of a textarea, but you can do that with contenteditable. What you should do is create a standard div (style it as a textarea) and make that contenteditable. Then put an onkey event in the div and check if the length is higher than 140. If it is get text, slice it, and apply an html to the excess.

Note that you want to get text content with element.textContent and write the html to element.innerHTML.

Another thing you should do is handle paste events because by default the browsers copy the html, so they will mess your contenteditable.

EDIT: If you have to use it in a form you need a textarea or an input hidden where to store the div content and send in the request.

To do that you can do something like this in jquery:

$('#form').submit(function(e) {
    var input = $('#inputdiv').text();
    if(input.length <= 140) {
        $('#formtextarea').val(input);
        return true;
    }
    return false;
});

Or you could do that with ajax.

function sendStuff() {
    $.post("test.php", { message: $('#inputdiv').text()})
    .done(function(data) {
         // do something here
    });
}
于 2013-06-05T21:43:38.833 に答える