jQuery - 父 div 内的随机定位 div

标签 jquery html css

我的问题如下:

我有三个不同类的 div,它们在一个更大的容器 div 中。
刷新页面后,有什么办法可以让它们在父div中随机定位?
使用下面的代码我几乎可以实现这一点,但有时一些 div 会从主 div 中掉出来。
任何帮助将不胜感激。

$(".img-1, .img-2, .img-3").each(function(index) {
  $(this).css({
    left: Math.random() * ($(".main").width() - $(this).width()),
    top: Math.random() * ($(".main").height() - $(this).height())
  });
});
.main {
  width: 512px;
  height: 512px;
  background-color: yellow;
}

.img-1 {
  width: 128px;
  height: 128px;
  background-color: blue;
}

.img-2 {
  width: 64px;
  height: 64px;
  background-color: green;
}

.img-3 {
  width: 32px;
  height: 32px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="img-1"></div>
  <div class="img-2"></div>
  <div class="img-3"></div>
</div>

最佳答案

您需要为 .img-X DIV 指定 position: absolute;,这样它们的位置将是相对于最近定位的祖先的绝对位置。然后你必须为 .main 使用 position: relative; 以便它满足该标准。

$(".img-1, .img-2, .img-3").each(function(index) {
  $(this).css({
    left: Math.random() * ($(".main").width() - $(this).width()),
    top: Math.random() * ($(".main").height() - $(this).height())
  });
});
.main {
  width: 512px;
  height: 512px;
  background-color: yellow;
  margin-top: 25px;
  position: relative;
}

.img-1 {
  width: 128px;
  height: 128px;
  background-color: blue;
  color: white;
  position: absolute;
}

.img-2 {
  width: 64px;
  height: 64px;
  background-color: green;
  color: white;
  position: absolute;
}

.img-3 {
  width: 32px;
  height: 32px;
  background-color: red;
  color: white;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="img-1">1</div>
  <div class="img-2">2</div>
  <div class="img-3">3</div>
</div>

关于jQuery - 父 div 内的随机定位 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47191982/

相关文章:

html - Angular 5 星评级栏

javascript - 如何从响应中获取数据数组(带有数组的对象)?

javascript - 根据主页中的选择值隐藏表单选择字段?

javascript - 将 div 添加到 slider

javascript - 使用 JQuery 构建 Tabs,最高效有效的方法?

html - div 或图像的覆盖层以显示不适用于伪元素的文本

html - 将文本与图像垂直对齐

javascript - 如何更改默认的 Onesignal 字体?

php - 如何将 setInterval 与 mouseenter 结合起来?

html - 当我在 Expo (iOS) 中使用 Print API 打印 html 时,html 中的分页符无法按预期工作