简体   繁体   中英

Sizing an absolute positioned element with Javascript

I'm trying to use a div element to mimic the effect of modal popup dialogs by masking the page when the hidden popup is displayed. I have managed to achieve my desired effect, but I run into a problem in that I am unable to size this masking element to match the size of the loaded page. If I just set the height of this div to an arbitrary height everything works fine, except my page ends up being much longer than the content.

Here is the javascript code I'm trying to set the height of the masking element with

function sizeModalDiv(){
  var ModalDiv = document.getElementById('ModalDiv'); 
  var FooterDiv = document.getElementById('FooterDiv');

  var FooterTop = FooterDiv.offsetTop
  var PageBottom = FooterTop + FooterDiv.clientHeight;
  ModalDiv.style.height = PageBottom+'px';
}

and here is my CSS for the masking element

#ModalDiv{
  position:absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4000px;
  z-index: 9999;
  background-color:Black;
  opacity: 0.7;
  visibility: hidden;
}

and this is the essence of my html code

<body>
  <div id="pagecontent">
    .......
    .......
    .......
  </div>
  <div id="ModalDiv"></div>
</body>

I've tried a number of different methods suggested here for dynamically sizing elements, but none seem to have any effect on the height of my masking element. It always remains at the height set in the CSS.

Where am I going wrong with this? I'm sure that it is something rather simple that I am missing and any help would be greatly appreciated.

To cover the whole window, you can use this CSS:

#ModalDiv{
  position:fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color:Black;
  opacity: 0.7;
  visibility: hidden;
}

A live demo at jsFiddle .

I think setting the CSS for html and body will overcome your issues. Also, remember to used position: fixed; for the popup if your page can have enough content to scroll (so the pop-up is on screen).

html{
 height: 100%;
 width: 100%;
 margin: 0;
 border: 0;
 padding: 0;
}

body{
 height: 100%;
 width: 100%;
 margin: 0;
 border: 0;
 padding: 0;
}

#ModalDiv{
  position:absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-color:Black;
  opacity: 0.7;
  visibility: hidden;
}

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