首页 > 解决方案 > 使两个文本区域同步水平滚动

问题描述

我有两个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>

标签: javascripthtmlcss

解决方案


做一个简单的滚动动作,这将取决于较低的滚动条在两个滚动条上相等。您必须将滚动条的值转换为百分比值。为此,下部文本区域中必须有一些可滚动的内容。

这是实现百分比值的函数的更新

function select_scroll(e) {
    let percent = bodybox.scrollLeft / (bodybox.scrollWidth - bodybox.clientWidth);
    headbox.scrollLeft =  (headbox.scrollWidth - headbox.clientWidth)* percent;
}

推荐阅读