简体   繁体   中英

How to make one Div's position (not child or parent) completely linked / dependent on another Div's position?

I have a bunch of functionality for manipulating one div's position and I need another div (not child or parent) to follow any position change automatically.

Here is a very simplified illustration: http://jsfiddle.net/ZHLD5/

<div id="follower"></div>
<div id="main"></div>

$('#main').draggable();

How to achieve this in CSS or jquery without changing html structure and without messing with selectors in draggable() and bunch of other codes?

So basically, how to make one div's position (not child or parent) completely linked / dependent on another div's position?

You can use CSS properties for this without having to use js. You can go to Overapi and check exactly how they work to understand them better. In my eyes you should do something like this:

<div class="page_holder">
 <div class="stuck"></div>
 <div class="page">
    <div class="container">
        <div class="content"></div>
    </div>
 </div>
</div>

And then...

.page_holder{
  position: absolute;
  top:50px;
  left:200px;
  width:200px;
  height:300px;
}
.page {
  position: absolute;
  top:0;
  left:0;
  width:200px;
  height:300px;
  overflow:auto;
  z-index: 1;
}
.container {
  position:relative;
}
.stuck {
  position: absolute;
  top:0;
  right:0;
  left:0;
  height:50px;
  background:blue;
  margin-right: 18px;
  z-index: 2;
}
.content {
  height:700px;
  background:gray;
}
$('#main').draggable({
  drag: function( event, ui ) {
    $('#follower').css({
      top: ui.position.top,
      left: ui.position.left
    });
  }
});

Another approach here

As long as you are using draggable(jQuery ui),You can easily achieve it like this. But since the function is called alot. don't forget to use id as the selector for performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM