首页 > 解决方案 > 如何阻止输入元素的焦点来回跳跃?

问题描述

我正在设计一个小型计算器应用程序,我尝试编写一个小而易于理解的不同代码来解释我的问题。
因此,当按下按钮时,它会生成随机数,然后进入输入框。现在,一旦输入框overflows,我已经设置了focus, 以便可以看到输入框中的内容。现在的问题是,观察溢出后,如果你按住按钮,焦点会回到左边,当你释放它时,焦点会回到右边,看起来很烦人,我只是想解决这个问题。我希望我想说的很清楚。

const input = document.querySelector('input');
const button = document.querySelector('button');

button.addEventListener('click', function() {
  // concatonate random number to input value
  input.value += Math.floor(Math.random() * 10)
  // focus input to scroll to end
  input.focus();
});
html, body {
  background: black;
}

input {
  width: 15rem;
	height: 3rem;
	margin: 2rem .4rem 2rem .4rem;
	font-size: 3rem;
  text-align: right;
  color: white;
  background-color: black;
  outline: none;
}
<input type='text' readonly='true' value='0'>
<button>CLICK ME</button>

标签: javascripthtmlcss

解决方案


只需添加direction: rtl;您的inputCSS。

const input = document.querySelector('input');
const button = document.querySelector('button');

button.addEventListener('click', function() {
  input.value += Math.floor(Math.random() * 10)
});
html, body {
  background: black;
}

input {
  width: 15rem;
	height: 3rem;
	margin: 2rem .4rem 2rem .4rem;
	font-size: 3rem;
  text-align: right;
  color: white;
  background-color: black;
  outline: none;
  transition: all .1s ease;
  direction: rtl;
}
<input type='text' readonly='true' value='0'>
<button>CLICK ME</button>

更新

根据您的最后一个链接https://codepen.io/ssmkhrj/pen/ExPjJab

这你应该在你的代码中改变

<div class="display-cover">
  <div class="display"></div>
</div>  

和 CSS

.display-cover{
  width: 19.2rem;
  height: 3rem;
  margin: 0 .4rem 1.5rem .4rem;
  text-align: right;
  font-size: 3rem;
  white-space: nowrap;
  padding-bottom: 0.5rem;
  overflow-y: hidden;
  overflow-x: scroll;
  scroll-snap-type: x mandatory; /* this will do the magic for parent */
}


.display{
  height: 3rem;
  display: inline-block;
  scroll-snap-align: end; /* this will do the magic for child */
}

更多关于scroll-snap这里https://css-tricks.com/practical-css-scroll-snapping/


推荐阅读