javascript - 使两个文本区域同步水平滚动
问题描述
我有两个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;
}
推荐阅读
- java - 使用 Hibernate 的 Eclipse 中出现 SSLException 错误,我该如何解决?
- matlab-guide - 如何修复'内部矩阵尺寸必须一致
- spring-boot - Spring Cloud Contract - 查询参数合约总是匹配同一个合约
- documentum - 有什么方法可以限制我访问我上传的文件?
- linux - 在 dlopen-ed 库中覆盖 malloc/free
- django - 如何部署 django 后端并将前端应用程序反应到同一域
- vue.js - VueJS - 如何在 Vue Router 中为任意数量的可选参数定义路由
- flask - flask-wtf 的字段定义中的 'name' 参数有什么作用?
- ruby-on-rails - 我的 Rails 表单没有被提交或重定向
- python - 如何使用 Python (requests-html) 在网站上获取 .xls 文件的文件名