开发者

Javascript: Detect Carets Parent Node

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.com/">Go|od stuff!</a> = You are Inside the a tag

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


MSIE lte 8: TextRange.parentElement()

Others: DOMRange.commonAncestorContainer

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

  var target=null;
  if(window.getSelection)
  {
    target=window.getSelection().getRangeAt(0).commonAncestorContainer;
    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.com/">Good stuff!</a>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜