使用 Isotope2 和 Scroll-js 滚动到点击的元素

Scroll to clicked element using Isotope2 and Scroll-js

我正在使用 Isotope2 and Scroll-JS on a project. There's a number of grid items in a Masonry layout. When a user clicks on a grid item it expands to full width and I want this item to scroll to the top of the viewport. My problem is that instead of scrolling from the current position within the page, the scroll starts from the top of the page. I've made a simplified case study in Codepen。我宁愿坚持香草 Javascript 而不是使用 jQuery.

这是我的 Javascript 到目前为止…

window._ = (...myvar) => console.log(...myvar);
const Services = {
  /**
   * default values for Isotope
   * @type {Object}
   */
  gridDefaults: {
    itemSelector: '.grid-item',
    percentPositions: true,
    masonry: {
      gutter: '.gutter-sizer',
      columnWidth: '.grid-sizer'
    }
  },

  clickedItem: null,

  /**
   * Initializes the module
   * @return {undefined} Executive method used to plug the module in.
   */
  init: () => {
    _('Services module initialized');
    Services.scroll = new Scroll(document.body);
    const grid = document.querySelector('.grid');
    const gridItems = grid.querySelectorAll('.grid-item');
    gridItems.forEach( gridItem => {
      gridItem.addEventListener('click', Services.Listeners.toggleExpand);
    });

  // call the Isotope function to process the grid element
    const iso = Services.iso = new Isotope( grid, Services.gridDefaults );
    iso.on('layoutComplete', Services.Listeners.scroll);
  },
  Listeners: {
    toggleExpand: function(e){
      const clickedGridItem = Services.clickedGridItem = Services.Helpers.clickedGridItem(e);
      clickedGridItem.classList.toggle('grid-item--width2');
      Services.iso.layout();
    },
    scroll: function(e) {
      _(Services.clickedGridItem);
      const scroll = Services.scroll;
      scroll.toElement(Services.clickedGridItem, {duration: 1000});
    }
  },
  Helpers: {
    clickedGridItem: function( eve ) {
      _(eve.path);
      return clickedItem = eve.path.find( (el) => 
        el.classList.contains('grid-item') );
    }
  }
};

Services.init();

这是 Scroll-JS 文档推荐的用于滚动到元素的内容(并且在测试中工作正常)

var myElement = document.body.getElementsByClassName('my-element')[0];
var scroll = new Scroll(document.body);
scroll
  .toElement(myElement)
  .then(function () {
    // done scrolling to the element
  });

这是 scroll-js 开发人员的回答。

@crs1138 there seems to be a problem with your example. all of the grid-items are absolutely positioned and the parent element ( in your example) has no overflow content. Per README, your parent element needs to always have overflow content.

In addition to that, I suspect there is something being done to the elements in the other JS files that is causing your page to redraw back to 0 in height.