我有一个行和列元素的表,每个元素包含一个或两个输入元素。
该表被限制在浏览器的可视区域内,通过包含在div中,该div使用overflow-x
/ overflow-y
滚动显示滚动条。
我的问题是在浏览每个元素时。 Tab键顺序是正确的,但是当到达水平行的末尾时,它有时会聚焦在输入上,而不会完全滚动显示它。
有什么方法可以在标签时轻松滚动整个输入?
输入仍然可以手动滚动到视图中,边界区域没有问题 我使用的是Chrome,只需针对此网站定位此浏览器。
答案 0 :(得分:1)
在文档上委派一个事件,以关注<input>
元素。 (addEventListener()
的第三个参数必须为true才能生效,因为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>
答案 1 :(得分:0)
您可以使用onFocus事件将div完全滚动到视图中。