1

我正在尝试(只是为了好玩)像 Facebook 这样的输入文本,用他们的文本区域,我的意思是,Facebook 的标签突出显示)。我正在关注这个问题来做到这一点。

我遇到了一些问题,因为我没有这个问题的相同 css,所以我想知道你是否可以帮助我解决这个问题。这是我正在谈论的“怪异”:

是的,有一些

这是我的代码:

// HTML
<div class="overlap" contenteditable='true'> </div>
<input type='text' class='medium-input' autocomplete='off'/> 

// JS
$('.medium-input').keyup(function (e) {
    var str =$('.medium-input').val();
    str = str.replace(/\n/g, '<br>');
    str = str.replace(/#([a-zA-Z0-9]+)/g, "<b>#$1</b>");
    $('.overlap').html(str);
});

// CSS
.medium-input, .overlap{
    width: 560px;
    position: relative;
    float: left;
    background-color: transparent;
    outline: 0;
    resize: none;
    direction: ltr;
}

.overlap{
    position:absolute;
    color:transparent;
    white-space: pre-wrap;
    max-width: 100%;
    height: 30px;
    padding: 7px 8px;
    font-family: sans-serif;
}

.overlap b{
    font-weight:bold;
    color:#333;
    display: inline-block;
    white-space: pre-wrap;
    word-wrap:break-word;
    direction: ltr; 
    text-align: left;
    max-width: 100%;
}

如您所见,我不太了解CSS和JS,我正在尝试自学,但是我遇到了这个问题,希望您能帮助我。

4

1 回答 1

1

更新

(见评论)

最简单的解决方案是使用textarea(with no-resize)。然后用一些 javascript 自动扩展它:

Updated Fiddle/ Javascript:

$(function () {
    var overlap = $('.overlap'),
        input = $('.medium-input');
    input.on('input', function () {
        overlap.html(this.value.replace(/#([a-zA-Z0-9]+)/g, "<b>#$1</b>"));
        input.height(overlap.height());
    });
});



使用粗体文本有点复杂。它占据了更多的空间,创造了这种“怪异”。
您可以使用文本阴影模拟粗体文本:

jsFiddle Demo/ CSS:

.medium-input, .overlap {
    position: relative;
    width: 560px;
    padding: 5px;
    background-color: transparent;
    border: 1px solid #999;
    outline: 0;
    font-size: 13px;
    font-family: sans-serif;
    word-spacing: 2px;
    color: #333;
    margin: 0;
}
.overlap {
    position: absolute;
    color: transparent;
    border: 1px solid transparent;
}
.overlap b {
    font-weight: normal;
    text-shadow: -1px 0 0 #666;
}

或者您可以简单地使用另一种样式方法:

jsFiddle Demo/ CSS:

.medium-input, .overlap {
    position: relative;
    width: 560px;
    padding: 5px;
    background-color: transparent;
    border: 1px solid #999;
    outline: 0;
    font-size: 13px;
    font-family: sans-serif;
    word-spacing: 2px;
    color: #333;
    margin: 0;
}
.overlap {
    position: absolute;
    color: transparent;
    border: 1px solid transparent;
}
.overlap b {
    font-weight: normal;
    background-color: #dedede;
    padding: 0 3px;
    margin: 0 -3px 0 -3px;
    border-radius: 3px;
    box-shadow: 0 0 0 1px #999;
}
于 2013-09-08T09:51:36.863 回答