Facebook Hashtags (Highlighting inside the textarea)

懵懂的女人 提交于 2020-08-25 03:23:29

问题


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 complex. Also backspace should remove the complete tag at once. Any way in which these hashtags can be implemented or any sample code implementing the same technique above?

As Html is highlighted here


回答1:


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

enter image description here

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




回答2:


you can make something like this:

http://jsfiddle.net/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;   
}


来源:https://stackoverflow.com/questions/23418383/facebook-hashtags-highlighting-inside-the-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!