简体   繁体   中英

Detecting offsetTop changes

I have a page which can't have scroll bars, so everything has to appear in the view all the time. On the image below you can see the basic setup of the screen, so you can get the representation of it.

样品

So, there are two blocks (1 and 2). The first one (1) is expandable, or it can even doesn't exist based on the content. The max-height is 500px for that block and I don't support mobile devices, only iPads and computers will be supported. The second block (2) exists all the time, no matter what.

The questions is: How to dynamically resize the second block, based on the offsetTop ?

Mainly I've tried to work with that through @ViewChild() , but it doesn't detect changes all the time and that makes the page to go beyond the view area.

This is how I've tried to work with that.

@ViewChild('block2') set offset(content: ElementRef) {
    content.nativeElement.style.maxHeight = `calc(100vh - ${this.offsetTop + 20}px)`;
}

Unfortunately, I can't share the source code, but any ideas will be highly appreciated.

The second block has to listen to the offsetTop changes all the time, and to fill the bottom space of the page.

You can handle this with just css, no need to use javascript (it makes complex and non optimized calculations that can be easily handled by your browser). Instead, use a flex box.

index.html

<div id="container">
  <div class="expandable">
    I am expandable
  </div>
  <div>
    I am not
  </div>
</div>

index.css

#container {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  /* Ensure your container takes the full screen */
  height: 100vh;
  width: 100vw;

  /* Here is the magic */
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

#container > *:not([class="expandable"]) {
  flex-grow: 1;
}

Now, you can programmatically set the height of your expandable div, and the second one will automatically resize, without flowing outside the screen.

EDIT

May not work perfectly like this, you may need to adjust one thing or two, depending on how your original project works. flex-grow , when applied to a flex child (not the flex container), will make the child expand automatically, to fill the remaining space.

More details here : MDN - Doc

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