当插入符号位于特定div / span / a标记内时,以及当插入符号离开标记时,触发事件 [英] Firing an event when the caret gets within a particular div/span/a tag and also, when the caret leaves the tag

查看:74
本文介绍了当插入符号位于特定div / span / a标记内时,以及当插入符号离开标记时,触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个想法是这样的 -
有一个可信的元素,里面有一些文字。我试图构建一个标记机制(类似于在键入'@'时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>

现在,每当用户将插入标记移动到标记/点击它时,我想触发显示弹出窗口的事件,并在插入符号离开标记时将其删除。 (有点像焦点/模糊,但它们似乎不起作用)。 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标记内时,以及当插入符号离开标记时,触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆