Trying to use Shuffle.js but getting Uncaught TypeError: Shuffle is not a constructor

Trying to use Shuffle.js but getting Uncaught TypeError: Shuffle is not a constructor

对于知情人士来说,这应该是一个足够简单的问题 - 为什么我的控制台会出现此错误?我尝试按照 Shuffle homepage 上 "usage" 下出现的代码进行操作,但我认为该页面忽略了包含开始使用该库的所有步骤。

这是我在安装库时创建的 shufflejs 文件夹中的索引文件中的代码。

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Shuffle Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">       
</script> 
</head>

<body>
<div id="grid" class="row my-shuffle-container">
<figure class="col-4@sm picture-item" data-groups='["photography"]' data-date-created="2010-09-14" data-title="Baseball">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/baseball.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>Baseball</figcaption>
</figure>
<figure class="col-4@sm picture-item" data-groups='["wallpaper","3d"]' data-date-created="2011-08-14" data-title="Tennis">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/tennis-ball.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>Tennis</figcaption>
</figure>
<figure class="col-4@sm picture-item" data-groups='["wallpaper","3d"]' data-date-created="2009-05-27" data-title="iMac">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/imac.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>iMac</figcaption>
</figure>
<div class="col-1@sm my-sizer-element"></div>
</div>

<script>
var Shuffle = window.shuffle;
var element = document.getElementById('grid');
var sizer = element.querySelector('.my-sizer-element');

var shuffle = new Shuffle(element, {
itemSelector: '.picture-item',
sizer: sizer // could also be a selector: '.my-sizer-element'
});
// Overrideable options
Shuffle.options = {
group: Shuffle.ALL_ITEMS, // Initial filter group.
speed: 250, // Transition/animation speed (milliseconds).
easing: 'ease', // CSS easing function to use.
itemSelector: '*', // e.g. '.picture-item'.
sizer: null, // Element or selector string. Use an element to determine     the size of columns and gutters.
gutterWidth: 0, // A static number or function that tells the plugin how wide the gutters between columns are (in pixels).
columnWidth: 0, // A static number or function that returns a number which tells the plugin how wide the columns are (in pixels).
delimeter: null, // If your group is not json, and is comma delimeted, you could set delimeter to ','.
buffer: 0, // Useful for percentage based heights when they might not always be exactly the same (in pixels).
columnThreshold: 0.01, // Reading the width of elements isn't precise enough and can cause columns to jump between values.
initialSort: null, // Shuffle can be initialized with a sort object. It is the same object given to the sort method.
throttle: throttle, // By default, shuffle will throttle resize events. This can be changed or removed.
throttleTime: 300, // How often shuffle can be called on resize (in milliseconds).
staggerAmount: 15, // Transition delay offset for each item in milliseconds.
staggerAmountMax: 250, // Maximum stagger delay in milliseconds.
useTransforms: true, // Whether to use transforms or absolute positioning.
};
</script>
</body>
</html>

您的代码未完成。创建随机播放主页效果 您的脚本应如下所示。

'use strict';

var Shuffle = window.shuffle;

var Demo = function (element) {
  this.element = element;

  // Log out events.
  this.addShuffleEventListeners();

  this.shuffle = new Shuffle(element, {
    itemSelector: '.picture-item',
    sizer: element.querySelector('.my-sizer-element'),
  });

  this._activeFilters = [];

  this.addFilterButtons();
  this.addSorting();
  this.addSearchFilter();

  this.mode = 'exclusive';
};

Demo.prototype.toArray = function (arrayLike) {
  return Array.prototype.slice.call(arrayLike);
};

Demo.prototype.toggleMode = function () {
  if (this.mode === 'additive') {
    this.mode = 'exclusive';
  } else {
    this.mode = 'additive';
  }
};

/**
 * Shuffle uses the CustomEvent constructor to dispatch events. You can listen
 * for them like you normally would (with jQuery for example). The extra event
 * data is in the `detail` property.
 */
Demo.prototype.addShuffleEventListeners = function () {
  var handler = function (event) {
    console.log('type: %s', event.type, 'detail:', event.detail);
  };

  this.element.addEventListener(Shuffle.EventType.LAYOUT, handler, false);
  this.element.addEventListener(Shuffle.EventType.REMOVED, handler, false);
};

Demo.prototype.addFilterButtons = function () {
  var options = document.querySelector('.filter-options');

  if (!options) {
    return;
  }

  var filterButtons = this.toArray(
    options.children
  );

  filterButtons.forEach(function (button) {
    button.addEventListener('click', this._handleFilterClick.bind(this), false);
  }, this);
};

Demo.prototype._handleFilterClick = function (evt) {
  var btn = evt.currentTarget;
  var isActive = btn.classList.contains('active');
  var btnGroup = btn.getAttribute('data-group');

  // You don't need _both_ of these modes. This is only for the demo.

  // For this custom 'additive' mode in the demo, clicking on filter buttons
  // doesn't remove any other filters.
  if (this.mode === 'additive') {
    // If this button is already active, remove it from the list of filters.
    if (isActive) {
      this._activeFilters.splice(this._activeFilters.indexOf(btnGroup));
    } else {
      this._activeFilters.push(btnGroup);
    }

    btn.classList.toggle('active');

    // Filter elements
    this.shuffle.filter(this._activeFilters);

  // 'exclusive' mode lets only one filter button be active at a time.
  } else {
    this._removeActiveClassFromChildren(btn.parentNode);

    var filterGroup;
    if (isActive) {
      btn.classList.remove('active');
      filterGroup = Shuffle.ALL_ITEMS;
    } else {
      btn.classList.add('active');
      filterGroup = btnGroup;
    }

    this.shuffle.filter(filterGroup);
  }
};

Demo.prototype._removeActiveClassFromChildren = function (parent) {
  var children = parent.children;
  for (var i = children.length - 1; i >= 0; i--) {
    children[i].classList.remove('active');
  }
};

Demo.prototype.addSorting = function () {
  var menu = document.querySelector('.sort-options');

  if (!menu) {
    return;
  }

  menu.addEventListener('change', this._handleSortChange.bind(this));
};

Demo.prototype._handleSortChange = function (evt) {
  var value = evt.target.value;
  var options = {};

  function sortByDate(element) {
    return element.getAttribute('data-created');
  }

  function sortByTitle(element) {
    return element.getAttribute('data-title').toLowerCase();
  }

  if (value === 'date-created') {
    options = {
      reverse: true,
      by: sortByDate,
    };
  } else if (value === 'title') {
    options = {
      by: sortByTitle,
    };
  }

  this.shuffle.sort(options);
};

// Advanced filtering
Demo.prototype.addSearchFilter = function () {
  var searchInput = document.querySelector('.js-shuffle-search');

  if (!searchInput) {
    return;
  }

  searchInput.addEventListener('keyup', this._handleSearchKeyup.bind(this));
};

/**
 * Filter the shuffle instance by items with a title that matches the search input.
 * @param {Event} evt Event object.
 */
Demo.prototype._handleSearchKeyup = function (evt) {
  var searchText = evt.target.value.toLowerCase();

  this.shuffle.filter(function (element, shuffle) {

    // If there is a current filter applied, ignore elements that don't match it.
    if (shuffle.group !== Shuffle.ALL_ITEMS) {
      // Get the item's groups.
      var groups = JSON.parse(element.getAttribute('data-groups'));
      var isElementInCurrentGroup = groups.indexOf(shuffle.group) !== -1;

      // Only search elements in the current group
      if (!isElementInCurrentGroup) {
        return false;
      }
    }

    var titleElement = element.querySelector('.picture-item__title');
    var titleText = titleElement.textContent.toLowerCase().trim();

    return titleText.indexOf(searchText) !== -1;
  });
};

document.addEventListener('DOMContentLoaded', function () {
  window.demo = new Demo(document.getElementById('grid'));
});

用这个替换你的脚本代码,它应该可以工作。

我遇到了同样的问题并通过将 shuffle.min.js 添加到我的文件而不是使用 CDN 来修复它。它仅使用:

var Shuffle = window.Shuffle;
var el = document.querySelector('#shuffle');
var shuffleInstance = new Shuffle(el,{
    itemSelector: '.item'
});

希望对您有所帮助。

您可以将其包装起来,以查看该页面上是否存在 div ID:

if ($('#my-shuffle-container').length > 0) {

}