In GMail you can add and modify contact details.

But the way you can do that is very neat.

Every field has some events like:

  • autosize textbox when you enter some text
  • onhover, change label to input field
  • onleave, change input field to label again.
  • auto save the content
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>");
});

I created a small example, but it's not ready yet.

jsfiddle.net/mJMpw/402

Does anyone have experience with this how Google does this.

There is still some work here

  • Validation, bouncing text when hover and leave

Any good libraries i can use to get the same result like Google input behavior?

有帮助吗?

解决方案

Managed to create a simpler way using the contenteditable attribute. Right now it isn't visually similar to Google's input, but there are no obstacles for that. In functionality, it works as you expect: Auto resize with minimum width, editable, but doesn't seem so when not hovered and handles "saving" when left.

$(".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>

It doesn't actually need jQuery, it is only used for the blur handler.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top