给定下面的js-bin,如果我在left
div中滚动(使用鼠标滚轮),它将在right
div中更新。
这是可行的,但如果你取消注释代码,它将不会滚动100px的鼠标滚轮(默认的铬鼠标滚轮行为)。(它会一个像素一个像素地滚动,这是我不想要的)。
基本上,我需要保持默认的铬鼠标滚轮滚动行为。
null
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.")
// });
null
使用setTimeout()
等待下一个刻度,然后修改代码,如下所示:
null
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>