使用纯JS创建具有id和样式的元素

时间:2015-02-25 18:19:24

标签: javascript function appendchild createelement

我构建了一个小函数,附加了一个带有id和样式的元素。 并且知道我的问题为什么这段代码不起作用?

    window.addEventListener("load",function(e){
        var inButton    = document.createElement("DIV"),
            body        = document.body;
        inButton.id = "button";
        inButton.style = function (){
            height       = "200px";
            width        = "400px";
            position     = "fixed";
            top          = "50%";
            left         = "50%";
            marginLeft   = -1*(this.width / 2);
            marginTop    = -1*(this.height / 2);
        };
        body.appendChild(inButton);
    }, false);

我使用以下html:         


        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8"/>
            <meta name="description"/>
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <meta http-equiv="x-ua-compatible" content="ie=edge" />
            <script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script>
        </head>
        <body>
        <script type="text/javascript" src="js/plugins.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
        </body>
        </html>

Js代码位于main.js。

我一次又一次地检查了路径,但路径完全正确。

1 个答案:

答案 0 :(得分:0)

您没有正确设置style属性。其余代码是正确的。

以下是

的示例

window.addEventListener("load", function(e) {
  var inButton = document.createElement("DIV"),
    body = document.body;
  inButton.id = "button";
  inButton.innerHTML = "Yahooooooooooooooo"; //For example

  inButton.style.height = "200px";
  inButton.style.width = "400px";
  inButton.style.position = "fixed";
  inButton.style.top = "50%";
  inButton.style.left = "50%";
  inButton.style.marginLeft = -1 * (this.width / 2);
  inButton.style.marginTop = -1 * (this.height / 2);

  body.appendChild(inButton);
}, false);