我正在运行以下代码,以根据内容调整输入的宽度。它工作得很好,除非我在末尾添加空格,否则文本将从框外移向左侧。我该如何像对待其他任何字符一样对待空格,以免打断框?
$.fn.liquidWidth = function(text, font) {
if (!$.fn.liquidWidth.fakeEl) $.fn.liquidWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.liquidWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));
var width = $.fn.liquidWidth.fakeEl.width();
if (this.data('liquid-min-width') != '' && width < this.data('liquid-min-width')) {
width = this.data('liquid-min-width');
} else if (this.data('liquid-max-width') != '' && width > this.data('liquid-max-width')) {
width = this.data('liquid-max-width');
}
if (width < 8) {
width = 8;
}
return width;
};
$(document).on('input', '.liquid-width', function() {
var inputWidth = $(this).liquidWidth();
$(this).css({
width: inputWidth
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something followed by a bunch of spaces...</p>
<input type="text" class="liquid-width" placeholder="text">
答案 0 :(得分:3)
那将无法正常工作,因为当您在标准HTML元素中添加 space 时,无论您将多少行放入其中,它都只会呈现一个空格,例如, input
,将它们全部呈现。
要使您的span
的大小也像input
,请使用white-space: pre
或将其“空格”替换为
堆栈片段
$.fn.liquidWidth = function(text, font) {
if (!$.fn.liquidWidth.fakeEl) $.fn.liquidWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.liquidWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));
var width = $.fn.liquidWidth.fakeEl.width();
if( this.data('liquid-min-width') != '' && width < this.data('liquid-min-width') )
{
width = this.data('liquid-min-width');
}
else if( this.data('liquid-max-width') != '' && width > this.data('liquid-max-width') )
{
width = this.data('liquid-max-width');
}
if( width < 8 ) { width = 8; }
return width;
};
$(document).on('input', '.liquid-width', function() {
var inputWidth = $(this).liquidWidth();
$(this).css({
width: inputWidth
});
});
span {
white-space: pre
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something followed by a bunch of spaces...</p>
<input type="text" class="liquid-width" placeholder="text">
答案 1 :(得分:1)
您必须在white-space:pre
上设置span
-然后它应该可以工作