关于自定义实现input

最近遇到一个功能,让input输入框根据输入内容的多少自己撑开宽度,试了试原生的input标签,发现有默认宽度,所以找了找原理,自己实现一个input

实现原理比较简单 动态获取dom元素增加input事件然后给想要显示的元素附上输入的内容

上效果图截图

 

上vue2示例代码

<template>
<div>

<div id="input-container">
<p id="input-text">请输入文本</p>
<span id="fake-input" placeholder="placeholder" contenteditable></span>
</div>
</div>
</template>

<script>
export default{
data(){
return{
text: '有默认值'
}
},
methods:{
},
mounted() {
const fakeInput = document.getElementById('fake-input');
const inputText = document.getElementById('input-text');

fakeInput.addEventListener('input', function() {
inputText.textContent = '您输入了: "' + fakeInput.textContent + '"';
this.text = fakeInput.textContent;
});
if (this.text) {
const fakeInput = document.getElementById('fake-input');
fakeInput.textContent = this.text
}

}
}
</script>
<style>
#input-container {
width: 300px;
border: 1px solid #ccc;
padding: 10px;
}

#fake-input {
display: inline-block;
//width: 100%;
max-width: 100%;
padding: 5px;
border: 1px solid #ccc;
outline: none;
text-align: left;
}

#fake-input:empty:before {
content: attr(placeholder);
color: #ccc;
}
</style>

  

 

posted @   Harry宗  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示