问题描述
想法是这样的-
有一个 contenteditable
元素,其中包含一些文本.我正在尝试建立一个标记机制(有点像 twitter 的人在你输入@"时标记).每当用户输入@"时,当他们继续输入时,它就会显示一个带有建议和过滤器的弹出框.直到这里这很容易,我已经弄清楚了.当/仅当插入符号位于包含标记的元素上方时,我需要显示弹出框时,问题就来了.
The idea is this -
There is a contenteditable
element with some text in it. Am trying to build out a tagging mechanism (kind of like twitter's people tagging when you type '@'). Whenever a user types '@', it shows up a popover with suggestions and filters when they continue typing. Until here it's easy and I have got it figured out. The problem comes when I need to show the popover if/only if the caret is over the element containing the tag.
<div contenteditable="">
<p>Some random text before
<a href="javascript:;"
class="name-suggest"
style="color:inherit !important;text-decoration:inherit !important">@samadams</a>
Some random text after</p>
</div>
现在,每当用户将插入符号移到 a 标签上/单击它时,我想触发一个显示弹出框的事件,并在插入符号离开 a 标签时将其删除.(有点像焦点/模糊,但它们似乎不起作用).onmousedown
有效,但无法判断光标是否已通过键盘移动到锚标记中.
Now, whenever the user moves the caret over the a tag / clicks on it, I want to trigger an event that shows the popover, and remove it whenever the caret leaves the a tag. (kind of like focus / blur but they don't seem to work). onmousedown
works but there is no way to tell if the cursor has been moved into the anchor tag with the keyboard.
另外,我在 angularjs 中这样做,因此,任何针对此的解决方案都是可取的,但不是必需的.
Also, am doing this in angularjs, so, any solution targeted towards that would be preferable but not necessary.
已经尝试让它工作一天,非常感谢任何帮助.
Have been trying to get this to work for a day and any help is greatly appreciated.
推荐答案
这将让您知道您的插入符号位置何时位于包含 @
This will let you know when your caret position is in an anchor node containing an @
$('#content').on('mouseup keydown keyup', function (event) {
var sel = getSelection();
if (sel.type === "Caret") {
var anchorNodeVal = sel.anchorNode.nodeValue;
if ( anchorNodeVal.indexOf('@') >= 0) {
$('#pop').show()
} else {
$('#pop').hide()
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" contenteditable="">
<p>Some random text before
<a href="javascript:;"
class="name-suggest"
style="color:inherit !important;text-decoration:inherit !important">@samadams</a>
Some random text after</p>
</div>
<div id="pop" style="display:none">Twitter node found</div>
您可以添加一些正则表达式来进一步验证选择.
You could add some regex to further validate the selection.
这篇关于当插入符号进入特定的 div/span/a 标签以及插入符号离开标签时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!