Javascript Travis J.如何将tempAlert置于中心位置

Javascript Travis J.如何将tempAlert置于中心位置,javascript,Javascript,我正在使用以下代码: 如何将邮件水平居中 function tempAlert(msg,duration) { var el = document.createElement("div"); el.setAttribute("style","position:absolute;top:40%;left:20%;background- color:white;"); el.innerHTML = msg; setTimeout(function(){ el.parentNode.remove

我正在使用以下代码:

如何将邮件水平居中

function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background-    color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}

您可以通过更改以下行使其居中:

    el.setAttribute("style","position:absolute;top:40%;width:100%;text-align:center;background-color:white;");

基本上,去掉“left:20%”并添加“text align:center”和“width:100%”

您可以对其应用
margin:auto
属性,它应该根据您所在的分区将其居中。您的函数如下所示:

function tempAlert(msg,duration)
{
     var el = document.createElement("div");
     // center, and apply an element width of 0
     el.setAttribute("style", "margin: auto;width: 0;");
     el.innerHTML = msg;
     setTimeout(function(){
      el.parentNode.removeChild(el);
     },duration);
     document.body.appendChild(el);
}
很好的参考


使用JSFIDLE

更改样式中的
left
的值?