开发者

Edit box: disable user formatting, but add my own

I know that rich text boxes in HTML is a bit of a minefield, but I'm hoping this particular situation won't be too tricky. I want a text box which the user can't format, but through scripting I can have it add some light formatting to (so a textarea won't work).

My first thought was that I could use a contentEditable, and if the user doesn't have a toolbar, they can't do much, but there's still the Ctrl + B, Ctrl + I, etc combinations. So I did this:

ctrlHandler = function (event) {
    event.preventDefault();
};

this.keydown(function (event) {
    if (event.ctrlKey) {
        $(this).bind('keypress', ctrlHandler);
    }
});
this.keyup(function (event) {
    if (event.ctrlKey) {
        $(this).unbind('keypress', ctrlHandler);
    }
});

So when the Ctrl key is pressed (keydown) an event handler is bound to keypress which prevents the default and when it's released the event handler is unbound. Clever, eh? (I'd work out how to handle cut/copy/paste etc combinations later.) With this, the event handler gets bound correctly, but event.preventDefault() doesn't actually prevent the default! The text gets made bold/italic/underli开发者_如何学Pythonned exactly as if I'd done nothing. The formatting change seems to happen before the event fires. Using keydown or keyup instead of keypress doesn't work either. Can anyone think of another (cross browser) approach, or how to make this one work?


Aha! It seems I've misunderstood what event.ctrlKey does. Pressing Ctrl + B doesn't fire two keydown events... it fires one with event.ctrlKey set to true. So if (event.ctrlKey) event.preventDefault() will do the trick. Not yet tested in all browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜