在浏览器窗口的顶部和底部动态创建元素

Dynamically Creating Elements at the Top and Bottom of Browser Window

本文关键字:底部 动态 创建 元素 顶部 浏览器 窗口      更新时间:2023-09-26

我使用下面的代码在浏览器窗口的顶部和底部动态创建一个"overlay" <div>

$(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>');
}

顶部的<div>正好出现在我想要的地方。

但底部的<div>不可见。当在谷歌浏览器中检查它时,它似乎表明它在窗口底部以下。

有人知道我在这里错过了什么吗?

编辑我的原始代码可以在http://jsbin.com/uravif/41

找到

也许我误解了,但你的代码似乎是为我工作(这里是小提琴)。

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>');

你只是在你的CSS中缺失:

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

否则使用你的"BTM"的bottom位置:)元素而不是top

编辑$(window).height()离线工作很好,所以我认为你是在搞乱jsBin的bug

<<p> jsbin演示/strong>

你可以使用一个bottom style属性:

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

bottom属性将元素定位在距离屏幕底部xx px处。

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>');
}