代码之家  ›  专栏  ›  技术社区  ›  KVNA

如何随机化聚合物中div的显示顺序

  •  1
  • KVNA  · 技术社区  · 8 年前

    我试图随机化聚合物中div的显示,但是在将这篇文章转换成框架时遇到了困难。

    Random Div Order on Page Load

    ready() {
      super.ready();
      let cards = this.shadowRoot.querySelectorAll('.className');
      for(var i = 0; i < cards.length; i++){
        let target = Math.floor(Math.random() * cards.length -1) + 1;
        let target2 = Math.floor(Math.random() * cards.length -1) +1;
        cards.eq(target).before(cards.eq(target2));
      }
    

    cards.eq 被称为。。。

    这能用一个 dom-repeat

    1 回复  |  直到 8 年前
        1
  •  1
  •   Umbo    8 年前

    链接的解决方案使用jQuery选择 div cards 是一个土著人的结果 querySelector eq 和 before 方法。

    这能用一个 dom-repeat ?

    <dom-module id="my-view">
      <template>
    
        <!-- Render the divs using dom-repeat -->
        <template is="dom-repeat" items="[[divs]]">
          <div>{{item.name}}</div>
        </template>
    
      </template>
    
      <script>
        class MyView extends Polymer.Element {
          static get is() { return 'my-view'; }
    
          static get properties() {
              return {
                  divs: {
                      type: Array,
                      value: [],
                  }
              };
          }
    
          // In connectedCallback you can initialise the divs property
          // by shuffling the initial ordered array using the Fisher-Yates algorithm
          // https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
          connectedCallback() {
              super.connectedCallback();
              let array = [ // The ordered model behind the divs
                  { name: 'Div #1' },
                  { name: 'Div #2' },
                  { name: 'Div #3' },
                  { name: 'Div #4' },
                  { name: 'Div #5' },
              ];
              let currentIndex = array.length, temporaryValue, randomIndex;
              while (0 !== currentIndex) {
                  randomIndex = Math.floor(Math.random() * currentIndex);
                  currentIndex -= 1;
                  temporaryValue = array[currentIndex];
                  array[currentIndex] = array[randomIndex];
                  array[randomIndex] = temporaryValue;
              }
              this.divs = array;
          }
    
        }
    
        window.customElements.define(MyView.is, MyView);
      </script>
    </dom-module>
    
    推荐文章