[Vuejs]-How can I control the move of blocks by a number I input in CSS and JS(or Vue)?

0👍

If you need a CSS-only solution, I don’t think this is possible (although I’m happy to be proven wrong by another poster).

One barebones way to do it would be using the CSS order property combined with a flexbox:

.container{
  display: flex;
  flex-direction: column;
  width: 300px;
}

input{
  margin: 20px;
}
<div class="container">
  <input oninput="this.style.order=this.value"/>
  <input oninput="this.style.order=this.value"/>
  <input oninput="this.style.order=this.value"/>
</div>

We subscribe to the oninput event here to update the order of the elements; this is a very minimal amount of JS. This solution has the (potentially large) downside of not being possible to animate, so if you wanted to smoothly slide the elements up & down into their new positions, then you could look into a solution like this one, or a more in-depth JS solution involving absolute positioning with a transition on the top, like this:

var inputs = [...document.querySelectorAll("input")];

function onInput(){
    inputs.sort((a, b) => (+a.value > 0 ? +a.value : 0) - (+b.value > 0 ? +b.value : 0));
  
  for (var i = 0; i < inputs.length; i++)
  {
    inputs[i].style.top = (i * 50) + "px";
  }
}
.container{
  width: 300px;
  position: relative;
}

input{
  margin: 20px;
  position: absolute;
  transition: all 1s;
}
<div class="container">
  <input oninput="onInput()" style="top: 0px"/>
  <input oninput="onInput()" style="top: 50px"/>
  <input oninput="onInput()" style="top: 100px"/>
</div>

You probably want to do some validation that the input is actually a number and not a string or other garbage, but hopefully this gets the idea across.

Leave a comment