您的位置:首页 > 产品设计 > UI/UE

input文本框自适应文本内容value宽度

2018-11-26 14:45 106 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" style="width: 100px ;font-size: 14px;" value="静静的敲代码" class="input_auto">
<input type="text" style="width: 100px;font-size: 20px" value="算了,先找对象吧"  class="input_auto">
<span  class="spanw"></span>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">

jQuery(document).ready(function($){
// 第一次加载设置input宽度
$('.input_auto').each(function(index, el) {
textWidth($(this))
});
// 改变文本内容时重置宽度
$('.input_auto').bind('input oninput', function() {
textWidth($(this))
});

function textWidth($this){
// 获取当前input的value值和字体大小
var inputVal=$this.val();
var font=$this.css('font-size');
//获取容器的宽度
$(".spanw").text(inputVal).css('font-size',font);;
var width = $(".spanw").width();
// 清空容器
$(".spanw").text('');
// 设置input宽度
$this.css('width', width);
};

});

</script>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: