简体   繁体   English

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

[英]Javascript: How to center multiple buttons that were created in Javascript using dynamically set CSS Style

I am trying to create a row of three buttons in Javascript using dynamically set CSS Style, but I am having difficulty trying to center the row of buttons in the middle of the page.我正在尝试使用动态设置的 CSS 样式在 Javascript 中创建一行三个按钮,但我在尝试将按钮行居中放置在页面中间时遇到困难。 This is with buttons that are currently not part of a div.这是当前不属于 div 的一部分的按钮。

I have tried button.align = 'center';我试过button.align = 'center'; with no success.没有成功。

Here is the link to jsfiddle snippet.这是jsfiddle片段的链接。

HTML SKELETON HTML 骨架

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

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

A quick solution would be adding text-align : center to the body一个快速的解决方案是将text-align : center添加到body

 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();
 body {text-align: center;}
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Buttons</title> </head> <body> <script> </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM