div模仿input框
2018-04-20 本文已影响807人
warryy
input 框中内容较多时,在 ios 端和华为mate(具体几忘记了)上出现内容无法左右滚动的 bug,所以想到用 div 来模拟 input 框的方法来解决此问题。
第一次想到用js来动态的添加或删除 input 框中的默认灰色文字
html:
<div class="imitate-input imitate-placeholder js-imitate-input" contenteditable="true">在此输入内容</div>
css:
<style>
.imitate-input{
width: 260px;
height: 16px;
border: 1px solid dodgerblue;
border-radius: 3px;
padding: 13px 10px;
size: 16px;
line-height: 16px;
outline: none;
color: #000;
}
.imitate-placeholder{
color: #999;
}
</style>
js:
<script>
// 获取元素
var jsInput = document.querySelector('.js-imitate-input');
// 获取焦点
jsInput.addEventListener('focus', function () {
if (jsInput.innerText == '在此输入内容'){
jsInput.classList.remove('imitate-placeholder');
jsInput.innerText = '';
}
});
// 失去焦点
jsInput.addEventListener('blur', function () {
if (jsInput.innerText == ''){
jsInput.classList.add('imitate-placeholder');
jsInput.innerText = '在此输入内容';
}
});
</script>
效果图:


但是如果我们点击输入框的时候点到了文字内容的时候:

输入框则会失去光标,并无法编辑内容:

辛亏让我遇到了这个bug,不然我就不会去问大牛,从而发现一个更好的实现方法:
用css来实现,无须js:
html:
<div class="imitate-input" contenteditable="true" placeholder="在此输入内容"></div>
css:
<style>
.imitate-input{
width: 260px;
height: 16px;
border: 1px solid dodgerblue;
border-radius: 3px;
padding: 13px 10px;
size: 16px;
line-height: 16px;
outline: none;
color: #000;
white-space: nowrap;
overflow-x: scroll;
overflow-y: hidden;
word-break: normal;
}
/* 清除左右滚动条 */
.imitate-input::-webkit-scrollbar{
display: none;
}
.imitate-input:empty:before{
content: attr(placeholder);
color: #999;
}
.imitate-input:focus:before{
content: none;
}
</style>
效果堪称完美:


本来以为完美的解决了问题,此时我的心情是这样的(~ ̄▽ ̄)~,但是测试小哥竟然在输入框中输入了空格和换行!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
结果页面结构成了这样:


此时如果我将数据传给后端,后端则出现了若干个问号。。。此问题目前没解决。所以个人目前没找到完美的 div 模仿 input 框方法,如果你被坑进来了,请不要 diss 我,因为我此时的心情(ಥಥ)(ಥಥ)(ಥ_ಥ)