在此示例中,我想在输入值宽度或光标越过输入宽度时显示警告。如何使用jQuery从输入字段获取值宽度而不是值长度?
$('.value_width').text($('.input').val().length); //this is just length of value but not value width
$('.input_width').text($('.input').width());
$('.input').keyup(function(){
$('.value_width').text($(this).val().length); //this is just length of value but not value width
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" name="" value="Example Text" />
<p/>
Value width : <span class="value_width"></span>
<br/>
Input width : <span class="input_width"></span>
&#13;
答案 0 :(得分:2)
你可以这样检查
$('.value_width').text($('.input').val().length);
$('.input_width').text($('.input').width());
$('.input').keyup(function(){
$('.value_width').text($(this).val().length);
if(22<=$(this).val().length){
alert('length filled');
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" name="" value="Example Text" />
<p/>
Value width : <span class="value_width"></span>
<br/>
Input width : <span class="input_width"></span>
&#13;