0

我正在使用 ckeditor.net 在电子邮件 CMS 中工作。在运行时用户可以更改电子邮件的正文,我想限制用户删除所有以 @@ 开头的特殊单词。

这是示例-

Email Alert! :<br />
<br />
**@@Comments**<br />
<br />
Please do not reply to this email.

我不希望用户删除其他电子邮件模板中的“@@comments”字和所有“@@”字符。你能给出任何 JavaScript 代码吗?

在运行时,我用某个段落替换“@@”字样。

4

1 回答 1

2

我还没有测试过这段代码(只是把它自由地写进了这个响应中),但这就是我要做的。

在文本输入的 keydown 方法上,您需要监听退格键

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    // Detect Backspace (8) & Delete (46) keys
    if( key == 8 || key == 46 ){

       var caretPos = getCaretPos(input);

       // Read backward from the caret position
       // until you hit a space or index 0:
       while ( (input.value[caretPos] != " ") && (caretPos > 0)  ){
          caretPos--;
       }

       // Once you hit the space or index 0, read forward two characters 
       // to see if it === "@@".  If both chars are "@", cancel 
       // the keydown event.  You should probably do some bounds checking
       // here.  Could also be done with String.subtring
       if ( input.value[(caretPos + 1)] == "@" && 
            input.value[(caretPos + 2)] == "@" )
       {
          return false;
       }
    }

};


function getCaretPos(input) {
    // Internet Explorer Caret Position (TextArea)
    if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        var bookmark = range.getBookmark();
        var caret_pos = bookmark.charCodeAt(2) - 2;
    } else {
        // Firefox Caret Position (TextArea)
        if (input.setSelectionRange)
            var caret_pos = input.selectionStart;
    }

    return caret_pos;
}

参考

检测退格

获取插入符号位置

取消keydown事件

于 2012-07-13T13:57:37.017 回答