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

Create Element with id and styles using pure JS

本文关键字:id 样式 元素 JS 创建      更新时间:2024-05-11

我构建了一个小函数,该函数附加了一个带有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.中

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

您没有正确设置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);