如何使用JavaScript将div随机放置在parent中?

时间:2019-05-04 09:19:30

标签: javascript

我有一个父div(fieldbox)和一个子div(potbox)。

在父级内部,我要在每次刷新页面时以 random 位置放置子级div。

由于某种原因,我的解决方案不起作用。我认为样式未定义。但是我不明白为什么...

const potboxRandom = document.querySelector('potbox')

const fieldWidth = 600;
const fieldHeight = 500;

randomTop = getRandomNumber(0, fieldWidth);
randomLeft = getRandomNumber(0, fieldHeight);

potboxRandom.style.top = `${randomTop}px`
potboxRandom.style.left = `${randomLeft}px`

function getRandomNumber(min, max) {
  return Math.random() * (max - min) + min;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.fieldbox {
  height: 500px;
  width: 600px;
  position: relative;
  background: lightskyblue;
}

.potbox {
  height: 20px;
  width: 20px;
  position: absolute;
  top: 100px;
  left: 100px;
  background: hotpink;
}
<div class="fieldbox">
  <div class="potbox"></div>
</div>

1 个答案:

答案 0 :(得分:1)

querySelector中只有一个选择器问题,请使用.potbox而不是potbox

const potboxRandom = document.querySelector('.potbox')

const fieldWidth = 600;
const fieldHeight = 500;

randomTop = getRandomNumber(0, fieldHeight - potboxRandom.clientHeight);
randomLeft = getRandomNumber(0, fieldWidth - potboxRandom.clientWidth);

potboxRandom.style.top = `${randomTop}px`
potboxRandom.style.left = `${randomLeft}px`

function getRandomNumber(min, max) {
  return Math.random() * (max - min) + min;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.fieldbox {
  height: 500px;
  width: 600px;
  position: relative;
  background: lightskyblue;
}

.potbox {
  height: 20px;
  width: 20px;
  position: absolute;
  top: 100px;
  left: 100px;
  background: hotpink;
}
<div class="fieldbox">
  <div class="potbox"></div>
</div>