我实现了一个 jQuery 插件来纠正 <input/>
的宽度元素取决于它们有多少文本,如下所示:
$.fn.correctWidth = function () {
var tempSpan = $('<span>')
.html(this.val())
.css('font-size', this.css('font-size'))
.insertBefore(this);
this.width(tempSpan.width());
tempSpan.remove();
return this;
};
问题是,有时,<span>
元素的宽度远大于实际文本宽度。
这个偶尔出现的问题似乎是因为检测到的宽度包括文本末尾和行尾之间的空白。
如何确保不包含空格?有替代方法吗?
最佳答案
尝试改变
this.width(tempSpan.width());
至
this.width(tempSpan.innerWidth());
关于javascript - 使用 `<span>` 技巧检测文本宽度时不包括空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290820/