Javascript动态添加左侧的div

时间:2018-04-08 19:58:22

标签: javascript jquery html css

目前它从left侧开始并将div's添加到right,但如何从左侧add div's创建first card。因此middle会显示在float: right中,并将其添加到后面(左侧)。

我已尝试设置var parentEl = document.getElementById("cards"); var elem = document.getElementById("myBar"); var width; var id; var parentEl = document.getElementById("cards"); var elem = document.getElementById("myBar"); var lastCard; var width; var id; function sortCards() { var cards = document.getElementsByClassName("card"), cw = parentEl.clientWidth, sw = parentEl.scrollWidth, diff = sw - cw, offset = diff / (cards.length - 1 ); for (var i = 0; i < cards.length; i++) { i != 0 && (cards[i].style.transform = "translateX(-" + offset * i + "px)"); } } //Move card document.getElementById("moveCard").addEventListener("click", function () { myMove(); }); //Start the game document.getElementById("play").addEventListener("click", function() { move(); }); //Stop the game document.getElementById("stop").addEventListener("click", function() { stop(); }); function move() { width = 1; id = setInterval(frame, 5); function frame() { if (width >= 100) { elem.style.width = 1 + '%'; clearInterval(id); addCard(); move(); } else { width++; elem.style.width = width + '%'; } } } function myMove() { var elem = lastCard; lastCard = lastCard.previousSibling; var pos = 0; var id = setInterval(movie, 5); function movie() { if (pos == 350) { clearInterval(id); elem.remove(); } else { pos = pos + 5; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; } } } function addCard(){ var div = document.createElement("div"); div.style.position = "relative"; div.style.color = "green"; div.style.left = "auto"; div.classList.add("card"); parentEl.appendChild(div); lastCard = div; sortCards(); } function stop() { elem.style.width = 1 + '%'; clearInterval(id); } sortCards();,但它没有提供想要的结果。

.cards {
  display: flex;
  max-width: 300px;
}

.card {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: red;
  transition: transform .25s;
}

.cardGreen {
 height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: green;
  transition: transform .25s; 
}

#myProgress {
    position: relative;
    width: 100%;
    height: 10px;
    background-color: grey;
}
#myBar {
    position: absolute;
    width: 1%;
    height: 100%;
    background-color: green;
}

/* Create three unequal columns that floats next to each other */
.column {
    float: left;
    /*padding: 10px;*/
    height: 300px; /* Should be removed. Only for demonstration */
}

.left, .right {
    width: 20%;
}

.middle {
    width: 60%;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	</head>
	<body>
        <header>
            <h1>Simple game</h1>
        </header>

        <div class="row">
            <div class="column left" style="background-color:#aaa;">
                <div><button class="btn btn-default btn-block" id="play">Start Game</button></div>
                <div><button class="btn btn-default btn-block" id="stop">Pause</button></div>

                <div><button class="btn btn-default btn-block" id="moveCard">Move Card</button></div>
            </div>
            <div class="column middle" style="background-color:#bbb;">
                <div class='cards middle' id="cards">
                    <!--<div class='cardGreen'></div>-->
                </div>
                <div id="myProgress">
                    <div id="myBar"></div>
                </div>
            </div>
            <div class="column right" style="background-color:#ccc;">

                <h2>Tutorial</h2>
                <p>Will be here soon :)</p>
            </div>
        </div>



        <script src="gamelogic.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </body>
</html>
library(tigris)
library(ggplot2)
library(ggthemes)
library(dplyr)

## Working Puerto Rico Map ----
# Downloads map
PR_map <- counties(72, cb = T) 
# Converts shapefile for ggplot2
PR_map <- ggplot2::fortify(PR_map, region = "COUNTYFP")
# Adds random data
PR_map <- merge(PR_map, data.frame(id = unique(PR_map$id), value = rep(1:4, (length(unique(PR_map$id)) %/% 4 + 4))[1:length(unique(PR_map$id))]), by = "id")
# Plots map
ggplot(PR_map)+geom_map(map = PR_map, aes(x=long, y=lat, fill = value, map_id=id), color="white", size=0.25)+ coord_map("mercator")+ theme_map()

## Broken Guam Map (No municipalities)----
# Downloads map
GU_map <- counties(66, cb = T) 
# Converts shapefile for ggplot2
GU_map <- ggplot2::fortify(GU_map, region = "COUNTYFP")
# Adds random data
GU_map <- merge(GU_map, data.frame(id = unique(GU_map$id), value = rep(1:4, (length(unique(GU_map$id)) %/% 4 + 4))[1:length(unique(GU_map$id))]), by = "id")
# Plots map
ggplot(GU_map)+geom_map(map = GU_map, aes(x=long, y=lat, fill = value, map_id=id), color="white", size=0.25)+ coord_map("mercator")+ theme_map()

## Broken Call for Mariana Islands 
# Does not download Mariana Islands, instead it downloads the entire United States and Territories 
USA_map <- counties(69, cb = T) 

# My work around is to subset to the appropriate region:
MI_map <- subset(USA_map, USA_map$STATEFP == "69")

# Converts shapefile for ggplot2
MI_map <- ggplot2::fortify(MI_map, region = "COUNTYFP")
# Adds random data
MI_map <- merge(MI_map, data.frame(id = unique(MI_map$id), value = rep(1:4, (length(unique(MI_map$id)) %/% 4 + 4))[1:length(unique(MI_map$id))]), by = "id")
# Plots map (The hex turns the map sideways for better viewing.)
ggplot(MI_map)+geom_map(map = MI_map, aes(x=long, y=lat, fill = value, map_id=id), color="white", size=0.25)+ coord_map("hex")+ theme_map()

任何提示或建议都会派上用场。

1 个答案:

答案 0 :(得分:2)

在父级的开头添加en元素而不是在结尾处,使用prepend代替append

  parentEl.prepend(div);
  

ParentNode.prepend方法在ParentNode的第一个子节点之前插入一组Node对象或DOMString对象。

这不会让第一张牌出现在中间,但是你必须重新调整你的牌位置。

var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var width;
var id;



var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var lastCard;
var width;
var id;



function sortCards() {
  var cards = document.getElementsByClassName("card"),
    cw = parentEl.clientWidth,
    sw = parentEl.scrollWidth,
    diff = sw - cw,
    offset = diff / (cards.length - 1);

  for (var i = 0; i < cards.length; i++) {
    i != 0 && (cards[i].style.transform = "translateX(-" + offset * i + "px)");
  }
}

//Move card
document.getElementById("moveCard").addEventListener("click", function() {
  myMove();
});


//Start the game
document.getElementById("play").addEventListener("click", function() {
  move();
});

//Stop the game
document.getElementById("stop").addEventListener("click", function() {
  stop();
});

function move() {
  width = 1;
  id = setInterval(frame, 5);

  function frame() {
    if (width >= 100) {
      elem.style.width = 1 + '%';
      clearInterval(id);
      addCard();
      move();
    } else {
      width++;
      elem.style.width = width + '%';
    }
  }
}


function myMove() {

  var elem = lastCard;
  lastCard = lastCard.previousSibling;

  var pos = 0;
  var id = setInterval(movie, 5);

  function movie() {
    if (pos == 350) {
      clearInterval(id);
      elem.remove();
    } else {
      pos = pos + 5;
      elem.style.top = pos + 'px';
      elem.style.left = pos + 'px';
    }
  }


}
var i = 1;

function addCard() {
  var div = document.createElement("div");

  div.style.left = "auto";


  div.innerHTML = i++;
  div.style.position = "relative";
  div.style.color = "green";


  div.classList.add("card");
  parentEl.prepend(div);
  lastCard = div;
  sortCards();
}


function stop() {
  elem.style.width = 1 + '%';
  clearInterval(id);
}

sortCards();
.cards {
  display: flex;
  max-width: 300px;
}

.card {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: red;
  transition: transform .25s;
}

.cardGreen {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: green;
  transition: transform .25s;
}

#myProgress {
  position: relative;
  width: 100%;
  height: 10px;
  background-color: grey;
}

#myBar {
  position: absolute;
  width: 1%;
  height: 100%;
  background-color: green;
}


/* Create three unequal columns that floats next to each other */

.column {
  float: left;
  /*padding: 10px;*/
  height: 300px;
  /* Should be removed. Only for demonstration */
}

.left,
.right {
  width: 20%;
}

.middle {
  width: 60%;
}


/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<header>
  <h1>Simple game</h1>
</header>

<div class="row">
  <div class="column left" style="background-color:#aaa;">
    <div><button class="btn btn-default btn-block" id="play">Start Game</button></div>
    <div><button class="btn btn-default btn-block" id="stop">Pause</button></div>

    <div><button class="btn btn-default btn-block" id="moveCard">Move Card</button></div>
  </div>
  <div class="column middle" style="background-color:#bbb;">

    <div class='cards middle' id="cards">
      <!--<div class='cardGreen'></div>-->

    </div>
    <div id="myProgress">

      <div id="myBar"></div>
    </div>
  </div>
  <div class="column right" style="background-color:#ccc;">

    <h2>Tutorial</h2>
    <p>Will be here soon :)</p>
  </div>
</div>

编辑:

要让第一辆车出现在中间,请设置父级的宽度0%,并在每次添加卡片时使其增长,直至到达100%,然后添加margin:auto

var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var width;
var id;



var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var lastCard;
var width;
var id;



function sortCards() {
  var cards = document.getElementsByClassName("card"),
    cw = parentEl.clientWidth,
    sw = parentEl.scrollWidth,
    diff = sw - cw,
    offset = diff / (cards.length - 1);

  for (var i = 0; i < cards.length; i++) {
    i != 0 && (cards[i].style.transform = "translateX(-" + offset * i + "px)");
  }
}

//Move card
document.getElementById("moveCard").addEventListener("click", function() {
  myMove();
});


//Start the game
document.getElementById("play").addEventListener("click", function() {
  move();
});

//Stop the game
document.getElementById("stop").addEventListener("click", function() {
  stop();
});

function move() {
  width = 1;
  id = setInterval(frame, 5);

  function frame() {
    if (width >= 100) {
      elem.style.width = 1 + '%';
      clearInterval(id);
      addCard();
      move();
    } else {
      width++;
      elem.style.width = width + '%';
    }
  }
}


function myMove() {

  var elem = lastCard;
  lastCard = lastCard.previousSibling;

  var pos = 0;
  var id = setInterval(movie, 5);

  function movie() {
    if (pos == 350) {
      clearInterval(id);
      elem.remove();
    } else {
      pos = pos + 5;
      elem.style.top = pos + 'px';
      elem.style.left = pos + 'px';
    }
  }


}
var i = 1;

function addCard() {
  var div = document.createElement("div");

  div.style.left = "auto";


  div.innerHTML = i++;
  div.style.position = "relative";
  div.style.color = "green";

  div.classList.add("card");
  if (parseInt(parentEl.style.width) < 100)
    parentEl.style.width = (parseInt(parentEl.style.width) + 10) + '%';

  parentEl.prepend(div);
  lastCard = div;
  sortCards();
}


function stop() {
  elem.style.width = 1 + '%';
  clearInterval(id);
}

sortCards();
.cards {
  display: flex;
  max-width: 300px;
}

.card {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: red;
  transition: transform .25s;
}

.cardGreen {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: green;
  transition: transform .25s;
}

#myProgress {
  position: relative;
  width: 100%;
  height: 10px;
  background-color: grey;
}

#myBar {
  position: absolute;
  width: 1%;
  height: 100%;
  background-color: green;
}


/* Create three unequal columns that floats next to each other */

.column {
  float: left;
  /*padding: 10px;*/
  height: 300px;
  /* Should be removed. Only for demonstration */
}

.left,
.right {
  width: 20%;
}

#cards {
  width: 15%;
  margin: auto;
}

.middle {
  width: 60%;
}


/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

<header>
  <h1>Simple game</h1>
</header>

<div class="row">
  <div class="column left" style="background-color:#aaa;">
    <div><button class="btn btn-default btn-block" id="play">Start Game</button></div>
    <div><button class="btn btn-default btn-block" id="stop">Pause</button></div>

    <div><button class="btn btn-default btn-block" id="moveCard">Move Card</button></div>
  </div>
  <div class="column middle" style="background-color:#bbb;">

    <div class='cards middle' id="cards" style="width:0%">
      <!--<div class='cardGreen'></div>-->

    </div>
    <div id="myProgress">

      <div id="myBar"></div>
    </div>
  </div>
  <div class="column right" style="background-color:#ccc;">

    <h2>Tutorial</h2>
    <p>Will be here soon :)</p>
  </div>
</div>