最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wysiwyg - Javascript: Detect Carets Parent Node - Stack Overflow

programmeradmin1浏览0评论

I'm building a simple WYSIWYG editor inside an iframe with designMode on , currently I can make the selected text bold, italic and underline and to link, and they work fine.

But I would like to know when the caret is inside the b, i, u, a, tags, so I can notify the user that the current selection is bold or whatever.

Examples:

Hello <b>Stackover|flow</b> is cool! = You are Inside the b tag

<i>Be|st place</i>! = You are Inside the i tag

Hello <a href="/">Go|od stuff!</a> = You are Inside the a tag

No libraries please I would like to learn this stuff :)

I'm building a simple WYSIWYG editor inside an iframe with designMode on , currently I can make the selected text bold, italic and underline and to link, and they work fine.

But I would like to know when the caret is inside the b, i, u, a, tags, so I can notify the user that the current selection is bold or whatever.

Examples:

Hello <b>Stackover|flow</b> is cool! = You are Inside the b tag

<i>Be|st place</i>! = You are Inside the i tag

Hello <a href="http://stackoverflow./">Go|od stuff!</a> = You are Inside the a tag

No libraries please I would like to learn this stuff :)

Share Improve this question edited Feb 6, 2011 at 14:54 Adam Halasz asked Feb 6, 2011 at 14:42 Adam HalaszAdam Halasz 58.3k67 gold badges153 silver badges216 bronze badges 4
  • Possible duplicate of this question – Tyler Holien Commented Feb 6, 2011 at 14:51
  • @Tyler Holien , I'm not talking about the caret position as a number, I would like to get it's Parent Node Name too, and the accepted answers solution works only on textareas. – Adam Halasz Commented Feb 6, 2011 at 14:53
  • True, sorry. Where is the caret, if not a textarea? – Tyler Holien Commented Feb 6, 2011 at 14:56
  • Nope :), I just edited my questions first line: I'm building a simple WYSIWYG editor inside an iframe with designMode on – Adam Halasz Commented Feb 6, 2011 at 14:58
Add a ment  | 

1 Answer 1

Reset to default 10

MSIE lte 8: TextRange.parentElement()

Others: DOMRange.monAncestorContainer

<script type="text/javascript">
<!--
function fx()
{

  var target=null;
  if(window.getSelection)
  {
    target=window.getSelection().getRangeAt(0).monAncestorContainer;
    return((target.nodeType===1)?target:target.parentNode);
  }
  else if(document.selection)
  {
    var target=document.selection.createRange().parentElement();
  }
  return target;
}
//-->
</script>
<input type="button" onclick="alert(fx().tagName)" value="click">
<div id="editor" contenteditable="true">
Hello <b>Stackoverflow</b> is cool! <i>Best place</i>
Hello <a href="http://stackoverflow./">Good stuff!</a>
</div>
发布评论

评论列表(0)

  1. 暂无评论