【发布时间】:2019-10-23 21:59:12
【问题描述】:
我正在尝试在 div 元素上复制输入水平滚动,因此每当用户沿输入移动时,div 元素的滚动与输入完全相同。
我的问题在于 Chrome,因为似乎输入具有不同的滚动行为,导致两个元素中的 scrollLeft 值不同。在 Firefox 中,它按预期工作。
有没有办法在 Chrome 中实现这一点不使用 jQuery 或其他库?还是我在问不可能?
var theTextDiv = document.getElementById("the-text");
var theText = document.getElementById("the-text-input");
function keepScroll(txt) {
theTextDiv.scrollLeft = theText.scrollLeft;
}
theText.addEventListener("blur", function() { keepScroll("blur"); });
theText.addEventListener("change", function() { keepScroll("change"); });
theText.addEventListener("focus", function() { keepScroll("focus"); });
theText.addEventListener("input", function() { keepScroll("input"); });
theText.addEventListener("keydown", function() { keepScroll("keydown"); });
theText.addEventListener("keyup", function() { keepScroll("keyup"); });
theText.addEventListener("scroll", function() { keepScroll("scroll"); });
theText.addEventListener("select", function() { keepScroll("select"); });
#the-text {
border: 1px solid red;
max-width: 98px;
font-size: 14px;
overflow-x: scroll;
word-wrap: break-word;
white-space: nowrap;
font-family: "Times New Roman", Times, serif;
padding: 1px;
margin-right: 10px;
}
#the-text-input {
border: 1px solid red;
width: 100px;
font-size: 14px;
font-family: "Times New Roman", Times, serif;
}
<div id="the-text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<input type="text" id="the-text-input" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
编辑:
我在 Mac 上的 Chrome 77 上尝试了上述代码,它按预期工作,两个元素之间没有差距,我开始认为这是 Windows 问题而不是 Chrome 问题
编辑(2):
重新启动我的电脑后,所有工作都按预期(严重)可能是某些 chrome 缓存导致出现奇怪的行为
【问题讨论】:
-
那是实际的代码吗?它似乎在 Chrome 77 上运行良好。
-
我已经用 Chrome 试过了,它可以工作。
-
适用于 Windows 10 上的 Chrome 77。
标签: javascript html css google-chrome firefox