我在项目中使用Isotope2和Scroll-JS。砌体布局中有许多网格项。当用户单击网格项时,它会扩展为全宽,我希望此项目滚动到视口的顶部。我的问题是,不是从页面中的当前位置滚动,而是从页面顶部开始滚动。我做了simplified case study in Codepen。我宁愿坚持使用Vanilla 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
});
答案 0 :(得分:0)
以下是 scroll-js 开发人员的答案。
@ crs1138你的例子似乎有问题。所有网格项都是绝对定位的,而父元素(在您的示例中)没有溢出内容。根据README,your parent element needs to always have overflow content。
除此之外,我怀疑其他JS文件中的元素正在进行某些操作,导致页面重绘为高度为0.