我正在尝试实现(只是为了好玩)一个输入文本,就像 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,我正在努力自学,但我遇到了这个问题,希望您能帮助我。
最佳答案
更新
(见评论)最简单的解决方案是使用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;
}
关于javascript - 输入中的粗体会导致奇怪的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673436/