Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - On div scroll activate another div's scroll

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();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want to respond to a scroll on one div by scrolling another.

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.

Example: Live Copy | Source

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...