我正在努力实现(仅仅是为了好玩)像Facebook这样的输入文本用他们的文本区域,我的意思是Facebook的标签荧光笔)。我正在关注this question这样做。
我遇到了一些问题,因为我对此问题没有相同的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,我正在尝试自己学习,但我遇到了这个问题,希望你能帮助我。
答案 0 :(得分:1)
最简单的解决方案是使用textarea
(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;
}