How to center tempAlert by Travis J

How to center tempAlert by Travis J

本文关键字:Travis by tempAlert to center How      更新时间:2023-10-03

我使用的是以下代码:

如何将消息水平居中?

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

基本上,去掉"左:20%",添加"文本对齐:居中"answers"宽度:100%"。

您可以将margin: auto属性应用于它,它应该根据您所在的div将其居中

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

很好的参考这里

在此处工作JSFiddle