在用户输入内容时,如何将内容可编辑div中以#
字符开头的所有单词的颜色更改为蓝色。它现在所做的只是所有匹配的颜色,但只有当它们出现在一个没有匹配的单词之后。像这样:
#life
随机#death
更多内容#trees
但这不起作用:
我吃了一个苹果#yum
#doctoraway
#healthy
#diet
这是一个小提琴: http://jsfiddle.net/GEm75/
我现在的做法是将每个匹配包装在一个范围内,然后用css设置它。我遇到一个问题,其中hashtag之后的非匹配文本仍然与hashtag的颜色相同。我解决了这个问题,但效率非常低,我非常想要一个替代方案。 这是我的代码:
<div id="box" style="border: 1px solid black; height: 10em" contenteditable="true">
</div>
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();
}
}
var inp = $('#box');
//select the box div
var text = '';
//#box's default value
inp.on('keyup', function(e) {
text = inp.html();
var matches_hash = text.match(/(^|\s)#(\w+)/g);
if (matches_hash) {
text = text.replace(/(^|\s)#(\w+)/g, "</span><span class='hashtag'> #$2</span><span class='else'>");
inp.html(text);
placeCaretAtEnd(document.getElementById('box'));
}
});
</script>
我想知道是否有更有效的方法来做到这一点。还有主题标签必须由非主题标签文本分隔的问题。我通过正则表达式测试器运行我的正则表达式,它工作正常。
函数placeCaretAtEnd(el)是由其他人制作的,我没有成功。但它所做的只是将插入符号放在可编辑div的末尾。
如果您有任何疑问,请发表评论
请帮帮我。
答案 0 :(得分:1)
有很多方法可以做到这一点,但这是一种方式背后的想法。希望它能让你的创意充满活力。
设置关系数据库(可能是MySQL)并创建一个post
表来存储帖子。假设post
表包含以下字段:
integer unsigned auto increment primary key id
timestamp posted
integer unsigned user_id
text comment
现在,您需要创建另一个表来存储主题标签。我们称之为hashtag
并使用此结构:
integer unsigned auto increment primary key id
integer unsigned post_id
text tag
post_id
表中的hashtag
会将您指向主题标签所属的post
行。现在,在MySQL中,您可以运行此查询:
SELECT post.* FROM hashtag LEFT JOIN post ON post.id = post_id WHERE tag = "life"
此查询将获取带有“life”主题标签的所有帖子。