admin管理员组

文章数量:1428923

I have this in my contenteditable div. Whenever I type #something, then type space, I would like to bold that word instantly in that div.

E.g.

This is my message. #lol. I would like to bold the hashtag.

Below is the code I have

<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){

  }
});

I am using jquery. How do i go about doing so?

I have this in my contenteditable div. Whenever I type #something, then type space, I would like to bold that word instantly in that div.

E.g.

This is my message. #lol. I would like to bold the hashtag.

Below is the code I have

<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){

  }
});

I am using jquery. How do i go about doing so?

Share Improve this question edited Apr 13, 2015 at 2:24 Christian 2,2001 gold badge19 silver badges35 bronze badges asked Jun 18, 2013 at 19:23 SlaySlay 1,2834 gold badges20 silver badges44 bronze badges 5
  • 1 Well, for one, you should be using .text() rather than .val() – crush Commented Jun 18, 2013 at 19:33
  • Why not use something like Stack O. uses (Markdown Editing): ** Bold text ** = Bold text It's much simpler to determine some text BETWEEN some characters, than your idea, cause you did not determine where should that bold end, which might not be exactly what you're looking for(?). Or at least something like #Bolded text here# normal weight... – Roko C. Buljan Commented Jun 18, 2013 at 19:34
  • What behavior do you wish to happen: Do you want the word to be bold as you write it, if you typed a # first? Do you want to bold the word after it's been written, if it is preceded by a #? – crush Commented Jun 18, 2013 at 19:34
  • @RokoC.Buljan It appears, though this is conjecture, that he wants the bold to end after the first word (space). – crush Commented Jun 18, 2013 at 19:35
  • Here is an example: jsfiddle/yBLVN – Roko C. Buljan Commented Jun 18, 2013 at 20:04
Add a ment  | 

2 Answers 2

Reset to default 2

Using contenteditable = "true" may be tricky, but this is a possible solution:

The text is bold when a word is preceded by #

  • Example: hello #world, this is a #sample

HTML:

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

JavaScript: jsbin./zisote

We are going to split the code, but actually it is wrapped in an 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();
  }
}

You can play with live code here: jsbin./zisote

Here is a sample. An editable div is not a good idea though. Try to change this. A textarea maybe is better...

http://jsfiddle/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();
        }
    }
});

本文标签: javascriptBold a specific text inside a contenteditable divStack Overflow