在div滚动上激活另一个div的滚动

时间:2013-05-04 17:04:00

标签: javascript jquery css html5

Jsfiddle

当我在滚动之外时,我尝试激活当前滚动,特别是在#DivDet

这是我试过的:

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

1 个答案:

答案 0 :(得分:33)

听起来你想通过滚动另一个div来回复一个scroll的滚动。

您已经确定了如何挂钩div事件。要设置元素的滚动位置(另一个scrollTop),请设置元素的scrollLeftscrollTop值(以像素为单位)。例如,如果您希望两个div以近似一致方式滚动,则会将源div scrollLeftdiv分配给目标(function() { var target = $("#target"); $("#source").scroll(function() { target.prop("scrollTop", this.scrollTop) .prop("scrollLeft", this.scrollLeft); }); })();

示例:Live Copy | Source

相关JavaScript:

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

或者(source):

<!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>

整页:

{{1}}