在 GMail 中,您可以添加和修改联系方式。
但是你可以做到这一点的方式非常简洁。
每个领域都有一些事件,例如:
- 输入某些文本时自动调整文本框大小
- 悬停时,将标签更改为输入字段
- onleave,再次将输入字段更改为标签。
- 自动保存内容
var controlfocused = false;
$(document).on("mouseover", "label.Editable", function () {
var txt = $(this).text();
$(this).replaceWith("<input id='hooverfield' class='hooverfield' data-autosize-input='{ 'space': 40 }'/>");
$("#hooverfield").val(txt).autosizeInput();
});
$(document).on("click", "input.hooverfield", function () {
controlfocused = true;
var txt = $(this).val();
$(this).replaceWith("<input id='Editfield' class='Editfield' type='text' data-autosize-input='{ 'space': 40 }'/>");
$("#Editfield").val(txt).autosizeInput();
});
$(document).on("mouseleave", "input.hooverfield", function () {
if(!controlfocused){
var txt = $(this).val();
$(this).replaceWith("<label class='Editable'>" + txt +"</label>");
}
});
$(document).on("blur", "input.Editfield", function () {
controlfocused = false;
var txt = $(this).val();
$(this).replaceWith("<label class='Editable'>" + txt +"</label>");
});
我创建了一个小示例,但尚未准备好。
有人有这方面的经验吗?Google 是如何做到这一点的。
这里还有一些工作
- 验证,悬停和离开时弹跳文本
我可以使用任何好的库来获得与 Google 输入行为相同的结果吗?
最佳答案
设法使用 contenteditable
属性创建一种更简单的方法。目前,它在视觉上与谷歌的输入并不相似,但没有任何障碍。在功能上,它按照您的预期工作:以最小宽度自动调整大小,可编辑,但在未悬停时似乎并非如此,并在离开时处理“保存”。
$(".google").blur(function(evt) {
//Insert real saving logic here.
console.log("Save things!");
});
* {
box-sizing: border-box;
}
.google {
display: inline-block;
height: 25px;
line-height: 25px;
width: auto;
border: none;
min-width: 80px;
font-family: sans-serif;
}
.google:hover, .google:focus, .google:active {
border: 1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="google" size="1" contenteditable="true">Hello</div>
它实际上并不需要 jQuery,它仅用于 blur
处理程序。
关于javascript - 创建输入字段,例如 Google 联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21517211/