我有一个包含行和列元素的表格,每个元素包含一个或两个输入元素。
表格被限制在浏览器的可视区域内,通过包含在使用 overflow-x
/overflow-y
滚动以显示滚动条的 div 中。
我的问题是在每个元素之间切换。 Tab 顺序是正确的,但是当到达水平行的末尾时,它有时会专注于输入而不是完全滚动以显示它。
有没有什么方法可以在使用 Tab 键时轻松地滚动到整个输入?
输入仍然可以手动滚动到 View 中,边界区域没有问题。
我正在使用 Chrome,并且只需要针对此网站定位此浏览器。
最佳答案
在文档上委托(delegate)一个事件以捕获对 <input>
的关注元素。 (addEventListener()
的第三个参数需要为真才能起作用,因为 focus
事件不会冒泡。)
在事件监听器中,如果源是 <input>
, 使用 getBoundingClientRect() 确定其最右边的边界强>。如果它大于其滚动容器的宽度,调整容器的 scrollLeft
根据需要显示整个 <input>
:
document.addEventListener('focus', function(e) {
var src = e.srcElement,
sLeft = src.getBoundingClientRect().left,
sRight = src.getBoundingClientRect().right,
container,
cWidth;
if (src.tagName === 'INPUT') {
container = src.parentNode;
while(container && !/auto|scroll/.test(window.getComputedStyle(container)['overflow-x'])) {
container = container.parentNode;
}
if(container) {
cWidth = container.clientWidth;
if (sRight > cWidth) {
container.scrollLeft += sRight - cWidth;
} else if (sLeft < 10) { //10 accounts for scrollbar arrow
container.scrollLeft += sLeft - 10;
}
}
}
}, true);
片段:
document.addEventListener('focus', function(e) {
var src = e.srcElement,
sLeft = src.getBoundingClientRect().left,
sRight = src.getBoundingClientRect().right,
container,
cWidth;
if (src.tagName === 'INPUT') {
container = src.parentNode;
while(container && !/auto|scroll/.test(window.getComputedStyle(container)['overflow-x'])) {
container = container.parentNode;
}
if(container) {
cWidth = container.clientWidth;
if (sRight > cWidth) {
container.scrollLeft += sRight - cWidth;
} else if (sLeft < 10) { //10 accounts for scrollbar arrow
container.scrollLeft += sLeft - 10;
}
}
}
}, true);
.container {
width: 300px;
overflow: auto;
white-space: nowrap;
}
input {
width: 140px;
}
input:focus {
background: yellow;
}
<div class="container">
<div>
<div>
1 <input type="text">
2 <input type="text">
3 <input type="text">
4 <input type="text">
5 <input type="text">
6 <input type="text">
</div>
</div>
</div>
关于javascript - 在 Tab 键上自动滚动以输入使其部分隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43741787/