javascript 在 div 滚动上激活另一个 div 的滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16376794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
On div scroll activate another div's scroll
提问by user2257991
回答by T.J. Crowder
It sounds like you want to respond to a scroll on one div
by scrolling another.
听起来您想div
通过滚动另一个来响应滚动。
You've already determined how to hook the scroll
event. To set the scroll position of an element (the other div
), you set the element's scrollTop
and scrollLeft
values (which are in pixels). If you want two divs to scroll in near-unison, for instance, you'd assign the source div's scrollTop
and scrollLeft
to the target div
.
您已经确定如何挂钩scroll
事件。要设置元素(另一个div
)的滚动位置,请设置元素的scrollTop
和scrollLeft
值(以像素为单位)。例如,如果您希望两个 div 几乎一致地滚动,则可以将源 div 的scrollTop
和分配给scrollLeft
目标div
。
Relevant JavaScript:
相关 JavaScript:
(function() {
var target = $("#target");
$("#source").scroll(function() {
target.prop("scrollTop", this.scrollTop)
.prop("scrollLeft", this.scrollLeft);
});
})();
or alternately (source):
或者(来源):
(function() {
var target = $("#target")[0]; // <== Getting raw element
$("#source").scroll(function() {
target.scrollTop = this.scrollTop;
target.scrollLeft = this.scrollLeft;
});
})();
Full page:
完整页面:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Scroll Example</title>
<style>
.scroll-example {
display: inline-block;
width: 40%;
border: 1px solid black;
margin-right: 20px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>Scroll the left div, watch the right one.</p>
<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>
<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>
<script>
(function() {
var target = $("#target");
$("#source").scroll(function() {
target.prop("scrollTop", this.scrollTop)
.prop("scrollLeft", this.scrollLeft);
});
})();
</script>
</body>
</html>