javascript - 如何阻止输入元素的焦点来回跳跃?
问题描述
我正在设计一个小型计算器应用程序,我尝试编写一个小而易于理解的不同代码来解释我的问题。
因此,当按下按钮时,它会生成随机数,然后进入输入框。现在,一旦输入框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>
解决方案
只需添加direction: rtl;
您的input
CSS。
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/
推荐阅读
- ssas-tabular - AnalysisServices:以表格形式对表进行可视化分组
- reactjs - Highmaps 加勒比地图
- java - 客户端 (X509) 认证的默认环境应该是什么
- ios - 如何将多个视图转换到同一位置(CGPoint)
- coldfusion - ColdFusion2016 服务未启动
- c# - 从数据库实体框架创建 JSON 列表
- pandas - 根据系列内容和数据框生成布尔数据框
- javascript - element.parentNode 从页面和 chrome 扩展上下文中为 Web 组件提供不同的结果
- nginx - nginx + socket + flask 的问题。握手后的504
- python - 如何使用 I2C 在 Raspi lcd 中格式化 12 小时时间