<分区>
标签 javascript jquery html css input
<分区>
我想知道输入框实际文字的宽度,而不是输入框的宽度。有没有等同于
$('#mybox').val().width();
准确测量文本占用多少像素? (这段代码显然行不通。)
最佳答案
像这样
$('input').on('keyup', function() {
var el = $('<div />', {
text : this.value,
css : {display : 'table-cell'}
}).appendTo('body');
var computedStyle = typeof this.currentStyle != 'undefined' ?
this.currentStyle :
document.defaultView.getComputedStyle(this, null);
$.each(computedStyle, function(_, style) {
if (style.indexOf('display') == -1 && style.indexOf('width') == -1)
el.get(0).style[style] = computedStyle[style];
});
var w = el.prop('clientWidth');
$(el).remove()
$('#width_output').html(w + 'px')
});
关于javascript - 如何获取输入文本的宽度(不是输入框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23094146/