首页 > 解决方案 > 单击提交按钮后如何根据文本值调整文本框的大小?

问题描述

在文本框中输入值并按下提交按钮后,如何根据里面的值调整文本框的大小。所以文本中心对齐显示正确(使用纯 javascript 或 css)。

<!DOCTYPE html>
<body>
  <div class="block">
    &#9728;
    <input type="text" id="inputValue" placeholder="Change City"></input>
    <button type="submit" id="submit">Submit</button>
  </div>  
<style>
  .block{
    border: 2px solid;
    width: 300px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  #inputValue{
    border: none;
  }
  #submit{
    display: none;
  }
</style>
<script>
  var inputValue = document.querySelector("#inputValue");
  var submit = document.querySelector("#submit");

  inputValue.addEventListener("click",function(){
    submit.style.display = "block";
  });

  submit.addEventListener("click",function(){
    submit.style.display = "none";
  });
</script>
</body>
</html>

标签: javascripthtmlcsstextboxwidth

解决方案


我给你举个例子。从这里开始的想法

<input class="txt" id="inputBox" type="text"><br>
<button onClick=test()>test</button>

function test(){

    var getClass = document.querySelector( ".txt" );
    var getValue = document.getElementById("inputBox").value.length

    getClass.style.width = ((getValue + 1) * 8) + 'px';
 }

除了这是另一种方法之外,这对您来说会更好。 点击这里

function test(){

    var getClass = document.querySelector( ".txt" );
  var getValue = document.getElementById("inputBox").value.length
  
  getClass.style.width = ((getValue + 1) * 8) + 'px';
}
<input class="txt" id="inputBox" type="text"><br>
<button onClick=test()>
  test
</button>


推荐阅读