您的位置:首页 > 其它

input宽度随内容变化

2020-02-03 04:42 4627 查看

今天收到一个需求,input的宽度随着内容的变化而变化,最重要的还有最大宽度的限制。

然后各种查资料个尝试,做了三个小案例:

一、获取文字数量*文字宽度去计算

虽然说这个方法代码量比较少,但是在不同的字体中还是有一定的误差的,所以建议不要使用,但是分享的角度来讲,我还是拿出来写一写。

<input type="text"/>
<script type="text/javascript">(www.gendan5.com)
$(function(){
$('input').on('keydowm keyup',function () {
var textLength = $(this).val().length,//获取input的文字数量
inputWidth = textLength*12;//12是字的宽度
$(this).width(inputWidth);
});
});
</script>
这个方法对于中文还是可以的,但是一般遇到中英文混合就不行了,所以如果是中英文混合的input我建议放弃。

二、利用scrollWidth来制作一个边长的(变不了短)

这个是有缺陷的,因为我们获取的是scrollWidth指,所以他只能获取最长的,而不能获取文字不撑开的时候的长度。

咱们直接贴代码把

<input type="text"/>
<script type="text/javascript">
$(function () {
$('input').on('keydowm keyup',function () {
var adad = $('input').get(0).scrollWidth;
console.log(adad);
$(this).width(adad);
})
})
</script>

三、文本比较法,这个方法虽然比较繁杂,但是无论误差还是可行性都是最高的

咱们先来个布局:

<div class="box">
<input type="text" value="请假"/>
<div></div>
</div>
<style>
.box div{ float:left;}
.box input{ width:80px; text-align:center;}
</style>
再来jq:

<script type="text/javascript">
$(function(){
function inputWidth(){
$('.box div').html($('.box input').val());//把input的文字给div
var inwidth = $('.box div').width();//获取div的宽度
if (80 < inwidth && inwidth < 800){
$('.box input').width(inwidth);//把div的宽度给input
};
};
inputWidth();
$('.box input').on('keydown keyup input',function(){//时时更新
inputWidth();
});
});
</script>
其实JQ和原生JS一样的道理,如果你使用JQ的直接拿走就可以了,如果是原生的按照这个想法写就可以了。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
cagwh9424 发布了0 篇原创文章 · 获赞 0 · 访问量 687 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: