如何使用createElement()重新创建整个div

时间:2017-02-19 17:54:29

标签: javascript html css sass

目前,我并不关心屏幕上显示的方框,我只想按下“运行”按钮并重新创建第一个方框。

我不知道我能为整个盒子做些什么来复制。

Demo

 document.getElementById("btn").onclick = function () {
var ok = true;

 if (ok === true) {
      var obj = document.createElement('div');
      obj.className = 'box';
   document.getElementsByTagName('body')[0].appendChild(obj);
}
}

1 个答案:

答案 0 :(得分:0)

JSfiddle会对你有用吗?



number = 0; //The index for the first div

document.getElementById("btn").onclick = function() {
  var ok = true;
  boxHTML = document.getElementsByClassName("box")[number].innerHTML;
  //Get innerHTML of the last box: "getElementsByClassName" returns an
  //array and the brackets contain a number that detemines which value
  //to be selected.

  number++; //Increment number

  if (ok === true) {
    var obj = document.createElement('div');
    obj.className = 'box box-' + number; //add class with number tag
    obj.innerHTML = boxHTML; //Give object same HTML
    document.getElementsByTagName('body')[0].appendChild(obj);
  }
};

//Boxes
@import url(https://fonts.googleapis.com/css?family=Roboto:400,700);
html,
* {
  box-sizing: border-box;
}

body {
  background: #e4e9f0;
  padding: 40px;
}

.box {
  float: left;
  position: relative;
  display: inline-block;
  width: 45%;
  background: white;
  padding: 30px;
  margin-right: 2%;
  margin-left: 4%;
  margin-top: 3%;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  overflow: hidden;
  +.box {
    margin: 0px;
    margin-top: 3%;
  }
  &:after {
    padding-top: 30%;
    /* 16:9 ratio */
    display: block;
    content: '';
  }
  >div {
    float: left;
    width: 100%;
    height: 150px;
    color: #fff;
  }
  header {
    background: #533687;
    display: block;
    margin: -30px -30px 30px -30px;
    padding: 10px 10px;
    h2 {
      line-height: 1;
      padding: 0;
      margin: 0;
      font-family: "roboto", sans-serif;
      font-weight: 600;
      font-size: 20px;
      color: white;
      -webkit-font-smoothing: antialiased;
    }
  }
}

<li><button id="btn">Run</button>
</li>
<div id="dashboard">
  <a href="#" class="box">
    <header>
      <h2>Responsive C3</h2>
    </header>
    <div id="chartA">
    </div>
  </a>
</div>
&#13;
&#13;
&#13;

注意:如果你使用jQuery,事情可能会容易得多。