小编tre*_*ver的帖子

Twitter如何实现其推文框?

我正在尝试实现Twitter的推文框,特别是:

  • 当总长度超过140个字符时,自动突出显示红色背景中的文本.
  • 自动以蓝色突出显示链接,提及和主题标签.

这些应该在用户输入时自动发生.

通过我在Twitter上看到的语义标记,看起来他们正在使用contentEditablediv.每当检测到提及/#标签/链接时,或者超过140个字符的长度时,都会修改DOM内部:

<div aria-labelledby="tweet-box-mini-home-profile-label" id="tweet-box-mini-home-profile" class="tweet-box rich-editor  notie" contenteditable="true" spellcheck="true" role="textbox" aria-multiline="true" dir="ltr" aria-autocomplete="list" aria-expanded="false" aria-owns="typeahead-dropdown-6">
    <div>hello world <a class="twitter-atreply pretty-link" href="/testMention" role="presentation"><s>@</s>testMention</a> text <a href="/search?q=%23helloWorld" class="twitter-hashtag pretty-link" role="presentation"><s>#</s>helloWorld</a> text <a href="http://www.google.com" class="twitter-timeline-link" role="presentation">http://www.google.com</a> text text text text text text text text text text text text text text <em>overflow red text here</em>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

到目前为止我做了什么

目前,我正在使用contentEditable字段.它会触发一个onChange/onInput解析文本的函数.通过regexr检查它是否有用户名/链接/主题标签,并用相应的标签替换它们(我现在只使用一个简单的<i>标签来包含用户名和主题标签). 我遇到的问题是因为我正在更改/修改contentEditable的DOM,所以插入符号光标位置会丢失. 我查看了这个线程在HTML中选择后保持范围对象的更改并且只有在未更改DOM时它才能正常工作(在我的情况下,它包含带有<i>标记的标记/主题标签,带有<a>标记的链接以及带有<b>标记的溢出).

小提琴:http://jsfiddle.net/4Lsqjkjb/

有没有人有解决这个问题的替代解决方案/方法?也许我不应该使用 …

html javascript twitter range selection

10
推荐指数
3
解决办法
3148
查看次数

标签 统计

html ×1

javascript ×1

range ×1

selection ×1

twitter ×1