在contenteditable的div中加粗特定文本

6

在我的可编辑区域里有这段内容。每当我打#某些东西,然后输入空格,我希望立即将该词加粗。

例如:

这是我的消息。 #笑死了。我想将井号加粗。

以下是我拥有的代码:

<div id="message" name="message" contenteditable="true"></div>

$('#message').keyup(function(e){

  var len = $(this).val().length;
  if ($(this).val().substring(length - 1, 1) == '#') {

  }

  //detect space
  if(e.keyCode == 32){

  }
});

我正在使用jQuery,如何开始使用它?


1
йҰ–е…ҲпјҢдҪ еә”иҜҘдҪҝз”Ё.text()иҖҢдёҚжҳҜ.val()гҖӮ - crush
为什么不使用类似 Stack O. 使用的 Markdown 编辑器:** 粗体文本 ** = 粗体文本。这种方式更容易确定在某些字符之间的一些文本,而不是你的想法,因为你没有确定粗体应该在哪里结束,这可能并不完全符合你的要求(?)。或者至少使用类似 #加粗文本# 正常字重... 的方式。 - Roko C. Buljan
您希望发生什么行为:如果您首先键入了“#”,您是否希望在写单词时将其加粗?如果单词之前有“#”,您是否希望将其加粗? - crush
@RokoC.Buljan 看起来,虽然这只是猜测,但他想让粗体在第一个单词(空格)后结束。 - crush
这是一个示例:http://jsfiddle.net/yBLVN/ - Roko C. Buljan
2个回答

2

使用 contenteditable = "true" 可能会比较棘手,但以下是一种可能的解决方案:

当一个单词前面有#时,该文本将会被加粗

  • 例如:你好#世界,这是一个#示例

HTML:

<div id="divEditable" contenteditable="true"></div>

JavaScript: jsbin.com/zisote

我们将要拆分这段代码,但实际上它被包裹在一个IIFE(立即调用函数表达式)中。

/*** Cached private variables ***/
var _break = /<br\s?\/?>$/g,
    _rxword = /(#[\w]+)$/gm,
    _rxboldDown = /<\/b>$/gm,
    _rxboldUp = /<\/b>(?!<br\s?\/?>)([\w]+)(?:<br\s?\/?>)?$/,
    _rxline = /(<br\s?\/?>)+(?!<b>)(<\/b>$)+/g;

/*** Handles the event when a key is pressed ***/
$(document).on("keydown.editable", '.divEditable', function (e) {
  //fixes firefox NodeContent which ends with <br>
  var html = this.innerHTML.replace(_break, ""),
      key = (e.which || e.keyCode),
      dom = $(this);

  //space key was pressed
  if (key == 32 || key == 13) {
    //finds the # followed by a word
    if (_rxword.test(dom.text()))
      dom.data("_newText", html.replace(_rxword, "<b>$1</b>&nbsp;"));
    //finds the end of bold text
    if (_rxboldDown.test(html))
      dom.data("_newText", html + "&nbsp;");
  }
  //prevents the bold NodeContent to be cached
  dom.attr("contenteditable", false).attr("contenteditable", true);
});

/*** Handles the event when the key is released ***/
$(document).on("keyup.editable", '.divEditable', function (e) {
  var dom = $(this),
      newText = dom.data("_newText"),
      innerHtml = this.innerHTML,
      html;

  //resets the NodeContent
  if (!dom.text().length || innerHtml == '<br>') {
    dom.empty();
    return false;
  }

  //fixes firefox issue when text must follow with bold
  if (!newText && _rxboldUp.test(innerHtml))
    newText = innerHtml.replace(_rxboldUp, "$1</b>");

  //fixes firefox issue when space key is rendered as <br>
  if (!newText && _rxline.test(innerHtml)) html = innerHtml;
  else if (newText && _rxline.test(newText)) html = newText;

  if (html) newText = html.replace(_rxline, "$2$1");

  if (newText && newText.length) {
    dom.html(newText).removeData("_newText");
    placeCaretAtEnd(this);
  }
});

/*** Sets the caret position at end of NodeContent ***/
function placeCaretAtEnd (dom) {
  var range, sel;
  dom.focus();
  if (typeof window.getSelection != "undefined"
  && typeof document.createRange != "undefined") {
      range = document.createRange();
      range.selectNodeContents(dom);
      range.collapse(false);
      sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
      //this handles the text selection in IE
      range = document.body.createTextRange();
      range.moveToElementText(dom);
      range.collapse(false);
      range.select();
  }
}

您可以在这里体验实时编码:jsbin.com/zisote

2
嗨,我发现这段代码有一个小错误。输入消息“#lol haha”,然后全部删除,再输入一些文本,它就会变成粗体了。你有什么想法是哪里出了问题吗? - Slay
问题仍然存在!要重现,请键入“#lol haha”,然后删除所有内容,再输入一些文字,它将会加粗。 - Slay

1
这是一个示例。可编辑的div并不是一个好主意。尝试更改此内容。使用textarea可能更好...

http://jsfiddle.net/blackjim/h9dck/5/

function makeBold(match, p1, p2, p3, offset, string) {
    return p1+'<b>' + p2 + '</b>'+p3;
};

$('#message').keyup(function (e) {
    var $this = $(this);

    //detect space
    if (e.keyCode == 32) {
        var innerHtml = $this.html();
        innerHtml = innerHtml.replace(/(.*[\s|($nbsp;)])(#\w+)(.*)/g, makeBold);

        if(innerHtml !== $this.html()){
            $this.html(innerHtml)
                 .focus();
        }
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接