编辑框:禁用用户格式,但添加我自己的格式
我知道 HTML 中的富文本框有点雷区,但我希望这种特殊情况不会太棘手。我想要一个用户无法格式化的文本框,但通过脚本我可以让它添加一些浅格式(因此文本区域不起作用)。
我的第一个想法是我可以使用 contentEditable
,如果用户没有工具栏,他们就不能做太多事情,但仍然有 Ctrl + B、Ctrl + I 等组合。所以我这样做了:
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);
}
});
因此,当按下 Ctrl 键(keydown
)时,事件处理程序将绑定到 keypress,这会阻止默认情况,并且当它被释放时,事件处理程序将被解除绑定。聪明吧? (稍后我会弄清楚如何处理剪切/复制/粘贴等组合。)这样,事件处理程序就可以正确绑定,但是 event.preventDefault()
实际上并没有阻止默认值!文本变成粗体/斜体/下划线,就像我什么也没做一样。格式更改似乎发生在事件触发之前。使用 keydown
或 keyup
而不是 keypress
也不起作用。任何人都可以想到另一种(跨浏览器)方法,或者如何使这个方法发挥作用?
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/underlined 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊哈!看来我误解了
event.ctrlKey
的作用。按 Ctrl + B 不会触发两个 keydown 事件...它会触发 event.ctrlKey 设置为 true 的事件。所以if (event.ctrlKey) event.preventDefault()
就可以了。尚未在所有浏览器中进行测试。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. Soif (event.ctrlKey) event.preventDefault()
will do the trick. Not yet tested in all browsers.