【发布时间】:2019-08-16 15:23:51
【问题描述】:
我有一个内容可编辑的 div,当用户点击空间或进入时,我用可点击的链接替换主题标签。用户写下:
我爱但是家里没有鱼|
然后他意识到自己犯了一个错误,然后决定回去写
我爱#sushi |但是家里没有鱼
#sushi
被替换为:
<a href="https://google.com/sushi>#sushi</a>
请注意 |显示用户按空格键时我希望插入符号所在的位置。我当前的“placeCaretAtEnd”函数将插入符号放在 div 的末尾,而不是在我刚刚替换 sushi 的链接后面。有没有办法改变我当前的功能,将插入符号放在我刚刚在上面显示的位置的文本中替换的链接后面,以便用户可以继续不小心输入?所以在原始html中:
我爱 #sushi |但是家里没有鱼
/**
* Trigger when someone releases a key on the field where you can post remarks, posts or reactions
*/
$(document).on("keyup", ".post-input-field", function (event) {
// if the user has pressed the spacebar (32) or the enter key (13)
if (event.keyCode === 32 || event.keyCode === 13) {
let html = $(this).html();
html = html.replace(/(^|\s)(#\w+)/g, " <a href=#>$2</a>").replace("<br>", "");
$(this).html(html);
placeCaretAtEnd($(this)[0]);
}
});
/**
* Place the caret at the end of the textfield
* @param {object} el - the DOM element where the caret should be placed
*/
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined"){
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true" class="post-input-field">
I love (replace this with #sushi and type space) but there is no fish at home
</div>
【问题讨论】:
标签: javascript jquery html replace caret