21

Jsfiddle

I trying to activate my current scroll while I am outside that scroll, specifically in #DivDet

here is what I tried:

$("div#DivDet").scroll(function () {
    // I don't know what i should have here      
    // something like $("div#scrlDiv").scroll();
});
4

1 回答 1

40

听起来您想div通过滚动另一个来响应滚动。

您已经确定了如何挂钩scroll事件。要设置元素(另一个div)的滚动位置,请设置元素的scrollTopscrollLeft值(以像素为单位)。例如,如果您希望两个 div 几乎一致地滚动,您可以将源 divscrollTop和分配scrollLeft给目标div

示例:Live Copy | 资源

相关的 JavaScript:

(function() {
  var target = $("#target");
  $("#source").scroll(function() {
    target.prop("scrollTop", this.scrollTop)
          .prop("scrollLeft", this.scrollLeft);
  });
})();

或交替(来源):

(function() {
  var target = $("#target")[0]; // <== Getting raw element
  $("#source").scroll(function() {
    target.scrollTop = this.scrollTop;
    target.scrollLeft = this.scrollLeft;
  });
})();

完整页面:

<!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>
于 2013-05-04T17:10:59.450 回答