如何使用Javascript或jQuery突出显示文本的前10个字符?

时间:2012-07-22 06:03:40

标签: javascript jquery

我想突出显示文本的前10个字符以及“段落”一词的颜色。

<html>
 <body>
  This is a heading
  This is a paragraph.This is another paragraph.
 </body>
</html>

2 个答案:

答案 0 :(得分:4)

将此视为您的HTML内容:

<div id="contents">
    This is a heading
    This is a paragraph.This is another paragraph.
</div>

这个jQuery代码可以满足您的需求:

$(document).ready(function() {
    var data = $('#contents').text().trim();

    var str = "";

    for(var i = 0; i < 10; i++) {
        str += data[i];
    }

    data = data.replace( /paragraph/g, '<span style="font-weight: bold;">paragraph</span>' );
    data = data.replace( str, '<span style="background-color: yellow;">' + str + '</span>' );

    $('#contents').html( data );
});

答案 1 :(得分:1)

在JS中尝试此代码。

<!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to highlight.</p>

    <p id="demo">This is a heading. This is a paragraph. This is another paragraph.</p>

    <button onclick="myFunction()">Try it</button>

    <script type="text/javascript">
    function myFunction()
    {
        var str= document.getElementById("demo").innerHTML;
        var str1 = "";

        for(var i = 0; i < 10; i++) {
            str1 += str[i];
        }
    var n=str.replace(str1,'<span style="font-weight: bold;">' + str1 + '</span>');
    document.getElementById("demo").innerHTML=n;
    }
    </script>

    </body>
    </html>