javascript - 使滚动条更新另一个滚动条,反之亦然
问题描述
鉴于以下js-bin,我该如何做到这一点,如果我在left
div 中滚动(使用鼠标滚轮)它将在right
div 中更新。
这可行,但是如果您取消注释代码,它将不再在鼠标滚轮处滚动 100 像素(默认 chrome 鼠标滚轮行为)。(它会逐像素滚动,这是我不想要的)。
基本上我需要保持默认的 chrome 鼠标滚轮滚动行为。
const target = $("#target");
$("#source").on("scroll", function (e) {
e.preventDefault()
target
.prop("scrollTop", this.scrollTop)
.prop("scrollLeft", this.scrollLeft);
console.log("Called.")
});
// $("#target").on("scroll", function (e) {
// e.preventDefault()
// $("#source")
// .prop("scrollTop", this.scrollTop)
// .prop("scrollLeft", this.scrollLeft);
// console.log("Called.")
// });
解决方案
使用 a等待Next TicksetTimeout()
并修改您的代码,例如:
const $scrollers = $("#target, #source");
let tickTimeout = null;
$scrollers.on("scroll", function(e) {
e.preventDefault();
const self = this;
const $other = $scrollers.not(self);
clearTimeout(tickTimeout);
tickTimeout = setTimeout(() => {
$other.prop({
scrollLeft: self.scrollLeft,
scrollTop: self.scrollTop,
});
}, 0);
});
.scroll-example {
display: inline-block;
width: 40%;
border: 1px solid black;
margin-right: 20px;
height: 100px;
overflow-y: auto;
}
<p>Scroll the left div, watch the right one.</p>
<div id="target" class="scroll-example">
1<br />2 <br />3 <br />4 <br />5 <br />6 <br />7 <br />8 <br />9 <br />10<br />11 <br />12 <br />13 <br />14 <br />15 <br />16 <br />17 <br />18<br />19 <br />20
</div>
<div id="source" class="scroll-example">
1<br />2 <br />3 <br />4 <br />5 <br />6 <br />7 <br />8 <br />9 <br />10<br />11 <br />12 <br />13 <br />14 <br />15 <br />16 <br />17 <br />18<br />19 <br />20
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
推荐阅读
- python - Python莳萝:KeyError:'ClassType'
- sql - SQL - 试图让员工的工资高于平均部门工资
- javascript - JavaScript window.location.href 在本地主机中不起作用
- python - 将索引浮点数转换回日期时间
- lua - Roblox Studio:NPC Humanoid,禁止攀爬
- terraform - 如何在“Terraform”中引用 aws_cognito_user_pools id?
- python - 模块 'turtle 没有监听成员。模块 turtle 没有“onkeymember”。
- html - 有没有办法在 css 中指定一个图像文件,以便根据 CSS 文件,图像是不同的?
- mysql - docker mysql 文件保存在本地系统的什么位置
- generics - 避免未经检查的演员表