Javascript:如何使用动态设置的CSS样式居中在Javascript中创建的多个按钮

时间:2018-02-06 18:09:29

标签: javascript html css

我正在尝试使用动态设置的CSS样式在Javascript中创建一行三个按钮,但是我很难尝试将按钮行放在页面中间。这是使用当前不属于div的按钮。

我尝试过 button.align =' center'; 但没有成功。

以下是指向jsfiddle代码段的链接。

HTML SKELETON          

  <head>
    <meta charset="utf-8">
    <title>Buttons</title>
  </head>

  <body>

    <script>
    </script>

  </body>

</html>

JAVASCRIPT

var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  // put the buttons on page
  document.body.appendChild(one);
  document.body.appendChild(two);
  document.body.appendChild(three);

}

buttonTest();

2 个答案:

答案 0 :(得分:1)

Link Here

var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  var divElem = document.createElement('div');
  divElem.setAttribute('style', 'text-align:center;');
  // put the buttons on page
  //document.body.appendChild(one);
  //document.body.appendChild(two);
  //document.body.appendChild(three);
  divElem.appendChild(one);
  divElem.appendChild(two);
  divElem.appendChild(three);
    document.body.appendChild(divElem);
}

buttonTest();

答案 1 :(得分:0)

快速解决方案是将text-align : center添加到body

&#13;
&#13;
var one, two, three;

function button(text) {
  var button = document.createElement('button');
  var buttonText = document.createTextNode(text);
  button.appendChild(buttonText);
  return button;

}

function buttonTest() {
  one = button('one');
  two = button('two');
  three = button('three');

  // put the buttons on page
  document.body.appendChild(one);
  document.body.appendChild(two);
  document.body.appendChild(three);

}

buttonTest();
&#13;
body {text-align: center;}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Buttons</title>
</head>

<body>

  <script>
  </script>

</body>

</html>
&#13;
&#13;
&#13;