简体   繁体   中英

Dynamically Creating Elements at the Top and Bottom of Browser Window

I'm using the following code to dynamically create an "overlay" <div> at the top and bottom of the browser window.

$(function() {
  var winWidth = $(window).width();
  var winHeight = $(window).height();
  $('body').append('<div style="position:fixed;left:0px;top:0px;width:' +
      winWidth + 'px;height:30px">TOP</div>');
  $('body').append('<div style="position:fixed;left:0px;top:' +
      (winHeight - 30) + 'px;width:' + winWidth + 'px;height:30px">BTM</div>');
}

The top <div> appears exactly where I want it to.

But the bottom <div> is not visible. When inspect it in Google Chrome, it seems to indicate that it is below the bottom of the window.

Can anyone see what I've missed here?

EDIT My original code can be found at http://jsbin.com/uravif/41

Maybe I'm misunderstanding, but your code seems to be working for me (here is the Fiddle ).

var winWidth = $(window).width();
var winHeight = $(window).height();
$('body').append('<div style="position:fixed;left:0px;top:0px;width:' +
      winWidth + 'px;height:30px">TOP</div>');
$('body').append('<div style="position:fixed;left:0px;top:' +
      (winHeight - 30) + 'px;width:' + winWidth + 'px;height:30px">BTM</div>');

you're just missing in your CSS:

body{
  height:100%; /* to fix jsBin bug with $(window).height() */
}

otherwise play with the bottom position of your "BTM" :) element instead of top of course.

edit $(window).height() will work great offline, so I just think you're messing with that jsBin bug

jsbin DEMO

there is a bottom style attribute that you can use for this:

$('body').append('<div style="position:fixed;left:0px;bottom:30px;width:' + winWidth + 'px;height:30px">BOTTOM</div>');

The bottom attributes positions the element at xx px from the botton of screen.

try below:

$(function() {
  var winWidth = $(window).width();
  var winHeight = $(window).height();
  $('body').append('<div style="position:fixed;left:0px;top:0px;width:' +
      winWidth + 'px;height:30px">TOP</div>');
  $('body').append('<div style="position:fixed;left:0px;bottom:0px;width:' + winWidth + 'px;height:30px">BTM</div>');
}

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