-1

我想创建一个div在随机位置放置多个材料设计图标的位置。

例如像这样:

图标集合

这是我使用 jQuery 制作的,但现在我想在 VueJS 中制作它,而不是使用形状,而是使用多个材料设计图标。

for (var i = 0; i < 10; i++) {
  $('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
  $(this).css({
    left : Math.random() * ($('.main').width() - $(this).width()),
    top : Math.random() * ($('.main').height() - $(this).height())
  });
});
.main {
  width: 600px;
  height: 400px;
  background: #f0f0f0;
  position: relative;
}

.box {
  width: 20px;
  height: 20px;
  background: black;
  border-radius: 50px;
  position: absolute;
  /* parent width - box width */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main"></div>

4

1 回答 1

1

Vue CLI生成的项目中使用单个文件组件的解决方案:

我们可以使用 Vue 的列表渲染来重新创建你的for-loop。我们添加模板引用并获取以下计算的元素引用.main.box

<template>
  <div ref="main" class="main">
    <div ref="box" class="box" v-for="i in 10"></div>
  </div>
</template>

根据元素参考,我们使用clientWidth和计算安装clientHeight时的盒子尺寸:

<script>
export default {
  async mounted() {
    // wait for $refs to be available
    await this.$nextTick()

    this.$refs.box.forEach(box => {
      box.style.left = Math.random() * (this.$refs.main.clientWidth - box.clientWidth) + 'px'
      box.style.top = Math.random() * (this.$refs.main.clientHeight - box.clientHeight) + 'px'
    })
  }
}
</script>

可以将原始 CSS 复制到一个<style>块中:

<style>
.main {
  /* insert original .main styles here */
}

.box {
  /* insert original .box styles here */
}
</style>

演示 1

您可以对 SVG 路径使用上述相同的步骤来加载随机的 Material Design 图标。例如,将 a 绑定<path>@mdi/js到来自(流行的 MDI 库)的随机 SVG 路径:

  1. 创建一个数据属性(名为"icons"),并使用随机范围的图标对其进行初始化@mdi/js

    import * as mdiIcons from '@mdi/js'
    
    function randomInt(min, max) {
      min = Math.ceil(min)
      max = Math.floor(max)
      return Math.floor(Math.random() * (max - min) + min)
    }
    
    function randomIcons(count) {
      const allIcons = Object.values(mdiIcons)
      const start = randomInt(0, allIcons.length - count)
      return allIcons.slice(start, start + count)
    }
    
    export default {
      data() {
        return {
          icons: randomIcons(10),
        }
      },
    }
    
  2. <div ref="box">将前面示例中的替换为<svg ref="box">。在里面<svg>,添加<path :d="icons[i]" />,它绑定到我们上面生成的随机图标。

    <template>
      <div ref="main" class="main">
        <svg ref="box" class="box" v-for="i in 10">
          <path :d="icons[i]">/>
        </svg>
      </div>
    </template>
    

演示 2

于 2020-12-21T20:03:31.283 回答