gpt4 book ai didi

javascript - contenteditable div 中的链接

转载 作者:行者123 更新时间:2023-11-30 12:52:02 25 4
gpt4 key购买 nike

我正在尝试创建一个可编辑的 div,它会定期检查输入的任何与 @text 匹配的文本(以@开头,以空格结尾)。

例如,如果用户输入 @text more text here , 它会将以 @ 开头并以空格结尾的单词更改为类似 <a href="#">@text</a> more text here 的链接在 div 中。

我已经开始使用 JSFiddle,但是,我无法让它工作:http://jsfiddle.net/MpFXK/2/

HTML:

<div class="box" contenteditable="true"></div>

JS:

$(document).on('keyup', ".box", function() {
var text = $(this).text();
var regexp = /\B@([^\B ]+)/;
if (text.match(regexp)) {
text = text.replace(/\B@([^\B ]+)/, '<a href="#">/\B@([^\B ]+)/</a> ');
return $(this).html(text);
}
return false;
});

请帮忙!

最佳答案

fiddle

$(document).on('keyup', ".box", function(e) {
if (e.keyCode == 32) {
var text = $(this).text();
var regexp = /(?=[@])[*@]\w+/;

var newText = text.replace(regexp, function(match) {
return '<a href="#">' + match + '</a>'
});
$(this).html(newText);
setEndOfContenteditable(this);
}
});

function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}

credit对于 setEndOfContenteditable 函数

关于javascript - contenteditable div 中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com