我有一個contenteditable
股利。我想將笑臉代碼替換爲keyup/keydown事件上的笑臉圖像。我已經理解了用於將笑臉代碼替換爲圖像的問題Replace smiley codes to images的標記答案代碼。在CONTENTEDITABLE DIV使用keyup事件的替換文本圖像
所以我試圖修改它KEYUP /的keydown事件,但是,它不工作。下面是修改後的代碼片段,其中回答了一個代碼。
var emoticons = {
':-)' : 'chair.gif',
':)' : 'cheers1.gif',
':D' : 'clapping.gif',
':-|' : 'dance.gif'
};
var url = "http://digitalsetups.com/emoji/";
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
// build a regex pattern for each defined property
for (var i in emoticons) {
if (emoticons.hasOwnProperty(i)){ // escape metacharacters
patterns.push('('+i.replace(metachars, "\\$&")+')');
}
}
// Building Regex Expression
var regex = new RegExp(patterns.join('|'),'g');
// My modification starts here to replace smiley code to image on keyup/keydown events
$(document).ready(function(){
$("#chatMessage").keyup(function(){
// var start = this.selectionStart;
$("#chatMessage").html($("#chatMessage").html().replace(regex,
\t \t \t \t function (match) {
\t \t \t \t return typeof emoticons[match] != 'undefined' ?
\t \t \t \t '<img src="'+url+emoticons[match]+'"/>' :
\t \t \t \t match;
\t \t \t \t }));
// this.selectionEnd = start;
});
});
#chatMessage {
max-height: 20px;
max-width: 400px;
overflow: auto;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<div id="chatMessage" contenteditable>This is contenteditable div. Press space to change :) into image. Or :-) into another image.</div>
</body>
</html>
UPDATE:
- 我已經更新了jQuery代碼。將
val()
更改爲html()
的keyup function()
定義。當我改變它的時候,代碼變成圖像 ,但光標移動到每一次我 寫1個字符的行首。 - 我試過
selectionStart
和 的解決方案selectionEnd
(我在代碼中評論過它)。沒有發生 。另外,如果我指定起始位置被選定結束 和結束位置被selectionStart然後,光標作品但 笑臉代碼不再改。
好吧。我已經將val()更改爲html(),現在它將代碼更改爲圖像,但它允許我只寫1個字符。只要我寫入1個字符,指針位置就會移動到div的開始位置。 –
@SumanKhan是的,因爲設置HTML會破壞div的前一個內容。要解決這個問題,你必須查看[Selection API](https://developer.mozilla.org/en-US/docs/Web/API/Selection)。這很糟糕,但是它完成了這項工作。 –
問題。 :/請參閱問題的更新部分。 –