我有两个textarea
框,我希望它们都能根据底部的滚动条同时水平滚动。只要两个textarea
框的文本量/宽度相同,我编写的以下程序就可以正常工作。正如你所看到的,我的第一个文本框比第二个文本框有更多的文本;因此,当我使用底部文本框的滚动条滚动时,我将看不到第一个框上的全文。请运行代码查看问题。有没有一种方法可以增加底部文本框区域的滚动区域,以匹配第一个框的滚动要求?
//Java Script Code
var headbox = document.getElementById('head_text_area');
var bodybox = document.getElementById('main_text_area');
bodybox.addEventListener('scroll', select_scroll, false);
function select_scroll(e) {
headbox.scrollLeft = bodybox.scrollLeft;
}
/*CSS style*/
#main_text_area, #head_text_area{
resize: none;
white-space: nowrap; /*All the text user types without pressing an enter should be in one line*/
width: 100%;
}
#head_text_area::-webkit-scrollbar {
display: none;/*First text box should not show a scroll bar*/
}
<textarea rows="6" id="head_text_area" width="100%" disabled>
This line is longer than the line in the second text area. At the start of the website, I won't be able to scroll to the right to see all the text in this area. Unless I put more texts on the bottom text area box.
More text might be here. The horizontal scroll bar of this section is hidden.
</textarea><br><br>
<textarea id="main_text_area" rows="6" width="100%">
This box isn't as long as the other text area. Therefore, scroll bar in this is short. This limits the viewable area of first box.
</textarea>
根据下一个滚动条,在两个滚动条上进行一个相等的简单滚动动作。您必须将滚动条的值转换为百分比值。要做到这一点,必须在较低的文本区域中有一些可滚动的内容。
以下是对实现百分比值的功能的更新
function select_scroll(e) {
let percent = bodybox.scrollLeft / (bodybox.scrollWidth - bodybox.clientWidth);
headbox.scrollLeft = (headbox.scrollWidth - headbox.clientWidth)* percent;
}