admin管理员组

文章数量:1314320

I want to highlight the text inside the textarea as facebook does. A solution to this is to keep an external div and highlight, as in this fiddle. But then there might be multiple highlighted field and then there position and width will have to be calculated at every instant, which seems very plex. Also backspace should remove the plete tag at once. Any way in which these hashtags can be implemented or any sample code implementing the same technique above?

I want to highlight the text inside the textarea as facebook does. A solution to this is to keep an external div and highlight, as in this fiddle. But then there might be multiple highlighted field and then there position and width will have to be calculated at every instant, which seems very plex. Also backspace should remove the plete tag at once. Any way in which these hashtags can be implemented or any sample code implementing the same technique above?

Share Improve this question edited May 1, 2014 at 23:37 red-devil asked May 1, 2014 at 23:26 red-devilred-devil 1,1031 gold badge22 silver badges37 bronze badges 1
  • Here is an angularjs directive which creates a content editable div with support for facebook like hashtags highlights github./sujeet100/ngHashtags Similar logic can be used to create what you want without using angularjs. – Sujit Kamthe Commented Jan 13, 2017 at 6:09
Add a ment  | 

2 Answers 2

Reset to default 10

The highlighting is occurring on a background layer that is updated on a keyup event listener (the textarea is transparent (background-color: rgba(0,​ 0,​ 0,​ 0))). This is what it looks like if you add some padding-top to the textarea (the highlight doesn't have an opportunity to update):

Facebook's approach is actually really clever, as you type in the text area the contents are evaluated and sent to a background element that looks like this:

<span class="highlighterContent"><b>#html</b> This is </span>

The <b> element has the following css:

.uiMentionsInput .highlighter b {
    background: linear-gradient(#DCE6F8, #BDCFF1) repeat scroll 0 0 rgba(0, 0, 0, 0);
    border-radius: 2px;
    box-shadow: 0 0 0 1px #A3BCEA;
    font-weight: normal;
}

The smart thing is the span behind the text area has a transparent font so it takes the same space as the opaque font of the text area (allowing the <b> highlight to stay aligned with the textarea text). Smart guys over there :)

you can make something like this:

http://jsfiddle/HR5N8/

<div id="something" contentEditable="true">
    Hi, my name is <span class="name">John</span> and i'm 20 years old!    
</div>

#something{
    width: 400px;
    height: 100px;
    border: 1px solid grey;
}

.name{
     background: #E1EEF5;   
}

本文标签: javascriptFacebook Hashtags (Highlighting inside the textarea)Stack Overflow