Javascript:用appendChild()创建一个div似乎不起作用

时间:2015-02-20 11:58:56

标签: javascript

我有一个AngularJS应用,我使用ui-router。我已经注入了第三方JS代码段,它应该创建一个div并将其附加到我的index.html文件的<body>,但它似乎无法正常工作。我的应用中没有创建div。

JS代码如下:

window.onload = function(){
  console.log('Initiated cursive.js');
  /*
  * Create topbar
  */
  var topBar = document.createElement('div');
  console.log(topBar);
  topBar.style.width = '100%';
  topBar.style.height = '20px';
  topBar.style.position = 'absolute';
  topBar.style.background = '#4C5264';
  topBar.style.top = '0';
  topBar.style.left = '0';
  /*
  * Append topbar to body
  */
  document.getElementsByTagName('body')[0].appendChild(topBar);
};

index.html文件:

<!doctype html>
<html lang="en">
  <head>
  ...
  </head>
  <body ui-view>
  ...
  </body>
</html>

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的代码是正确的,并且工作正常。由于其他一些控件,你可能不会看到topBar div。要确保topBar在DOM中,您可以将z-index设置为9999,在这种情况下,您的topBar div应该可见。

topBar.style.zIndex = 9999;