可编辑且宽度自适应input

默认的input项是比较难看的,并且它的宽度还无法随着输入而变化,这样未免有些呆板,不过借助JavaScript可以达到宽度自适应的效果,下面为了方便使用了jQuery:

<div class="list">
    <span class="list_name">娉娉袅袅</span>
    <input type="text" class="list_name hidden">
</div>
.hidden{
      display: none;
    }

    .list{
      background-color: #303030;
      color: aliceblue;
      display: inline-block;
      font-size: 2rem;
      padding: 0.5rem 1.5rem;
      border-radius: 1rem;
    }
    input{
      border: none;
      outline: none;
      font-size: 2rem;
      background-color: transparent;
      color: #F16665;
      caret-color: aliceblue;
    }
var $span = $("span.list_name");
    var $input = $("input.list_name");
    function onEdit($span){
      $span.hide()
        .siblings("input.list_name")
        .val($span.text())
        .show()
        .focus();
    }
    $span.click(function(){
      onEdit($(this));
    });
    $input.bind("keydown", function(e){
      if(e.keyCode == "13"){
        $(this).hide()
        .siblings("span.list_name")
        .text($(this).val())
        .show();
      }
    })
    $input.bind("blur", function(){
      $(this).hide()
        .siblings("span.list_name")
        .text($(this).val())
        .show();
    });
    $("input[type='text']").bind("focus",function(){
      $(this).css("width",$(this).val().length + "em");
    })
    $("input[type='text']").bind("input propertychange",function(){
      $(this).css("width",$(this).val().length + "em");
    })

点击此查看样例

猜你喜欢

转载自www.cnblogs.com/lotusloli/p/10567616.html