2
4

3 回答 3

3

最简单的方法:

$('div').replace( /\#(\S+)/g, "<b>$1</b>" )

这是一个工作小提琴:http: //jsfiddle.net/7cGCZ/2

于 2013-06-22T23:40:26.663 回答
2

试试.replace(),比如:

var sid = $('#someDIV').html();
$('#someDIV').html(sid.replace(/(#\S+)\s/g, '<b>$1</b> '));
于 2013-06-22T23:52:03.650 回答
0

对于任何面临相同问题并想学习的人来说,这就是我想要实现的目标。

CSS:

.TextArea {
    width: 300px;
    height: 30px;
    border: 1px solid rgb(204, 204, 204);
    margin: 0px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    Padding: 5px;
    color: #444;
    -webkit-text-fill-color: transparent;
    resize: none;
    outline: 0;
    z-index: 2;
    background-color: transparent;
    position: relative;
    font-family: Arial,Helvetica,Verdana,sans-serif;
    line-height: 1.28;
    font-size: 12px;
}
.DivTag {
    position: absolute;
    z-index: 1;
    border: 1px solid rgb(204, 204, 204);
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    background-color: white;
    zoom: 1;
    border-radius: 5px;
    padding: 5px;
    width: 300px;
    height: 30px;
    line-height: 1.28;
    overflow: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
    font-family: Arial,Helvetica,Verdana,sans-serif;
    font-size: 12px;
}

.boldTag {
    background: #d8dfea;
    background: -webkit-gradient(linear, center top, center bottom, from(#dce6f8), to(#bdcff1));
    background: -webkit-linear-gradient(#dce6f8, #bdcff1);
    -webkit-border-radius: 2px;
    -webkit-box-shadow: 0 0 0 1px #a3bcea;
    font-weight: normal;
}

HTML:

<div class = "DivTag"></div>
<textarea class="TextArea"></textarea>

查询:

$('.TextArea').keyup(function () {
        var txt = $('.TextArea').val();
        $(".DivTag").text(txt);
        var DivTag = $(".DivTag").text();
        var $div = $(".DivTag");
        $div.html(DivTag.replace(/\s(\#[a-zA-Z]\w*)/g, " <b class='boldTag'>$1</b>"));
        text = $(".DivTag").text();
        text = text.replace(/\s+/g, " ");
        text = text.trim();
});

示例:http: //jsfiddle.net/7cGCZ/3/

于 2013-06-25T11:59:52.133 回答