[英]How to restrict user from deleting words with special characters from textbox
我正在使用ckeditor.net在電子郵件CMS中工作。 在運行時用戶可以更改電子郵件的正文,我想限制用戶刪除所有以@@開頭的特殊單詞。
這是一個例子 -
Email Alert! :<br />
<br />
**@@Comments**<br />
<br />
Please do not reply to this email.
我不希望用戶刪除其他電子郵件模板中的“@@ comments”字樣和所有“@@”字符。 你能用JavaScript代碼嗎?
在運行時,我用一些段落替換“@@”字。
我沒有測試過這段代碼(只是自由形成了這個代碼),但這就是我要做的。
在文本輸入的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;
}
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.