繁体   English   中英

如何突出显示textarea中的一部分文本

[英]How to highlight a part of text in textarea

有没有办法突出显示文本区域中的一部分文本?

说,文Hi @twitter @twitpic ,现在我想强调@twitter,只和不@twitpic 这可能吗?

这必须即时发生。

PS:我不想使用iFrame

提前致谢

在该文本上使用setSelectionRange方法

示例代码:

<body>
    <section>
        <textarea id="textarea"></textarea>
        <button id="hgh">Hightlight @twiiter</button>
    </section>

    <script>

        window.onload = function () {

            var textarea = document.getElementById("textarea");
            var checkError = document.getElementById("hgh");

            checkError.addEventListener("click", function () {

                var index = textarea.innerText.indexOf("@twitter");
                if( index >= 0)
                    textarea.setSelectionRange(index, index + 8);
            });
        }

    </script>
</body>

如果没有在特定单词周围包裹标签,您就无法突出显示它(或者正如我所说,至少我不知道如何)。 但是如果包装标签没有问题,你应该使用regEx。

对于以 @ 开头的单词:

replace(/@([^ ]+)/g, '<span class="atsign">@$1</span>');

对于以 # 开头的单词:

status.replace(/#([^ ]+)/g, '<span class="hashtag">#$1</span>');

检查这个小提琴

编辑:你可以更换

var status = 'I tweeted something #one #two @three @four';

var status = $('#phrase').text();

我来这里是为了寻找一个可以突出显示文本区域中某些单词的答案。 在这个线程中没有找到答案。 所以,补充一下我是怎么做的:

对于此示例,您将执行以下操作:

  1. 从这里下载并包含脚本: http : //garysieling.github.io/jquery-highlighttextarea/index.html

  2. 并使用这个:

     <script> $('textarea').highlightTextarea({ words: ['@twitter', '@twitpic'], id: 'demoCustom', caseSensitive: false // or a regular expression like -> words: ['@([^ ]+)'] }); </script> <style> #demoCustom mark { padding:0 3px; margin:-1px -4px; border-radius:0.5em; border:1px solid pink; } </style>

更多示例: http : //garysieling.github.io/jquery-highlighttextarea/examples.html

使用jQuery非常简单。

HTML部分:

<textarea id="test">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam rhoncus aliquam metus. Praesent vitae arcu tempor neque lacinia pretium.</textarea>
<button id="search">search</button>

JS部分:

$(function(){
  $("#search").click(function(){
    var area   = $('#test');
    var findWord = "rhoncus";
    var index = area.val().indexOf(findWord);
    area.focus().prop({'selectionStart': index, 'selectionEnd': index+findWord.length})          
  })
})

只需更改变量 findWord 即可突出显示任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM