我希望在单击按钮时能够平滑自动滚动到 Polymer 1.0 铁列表中的特定元素。
现在,由于 scrollToIndex 方法,我有了一个简单的自动滚动。
但我想要一个流畅的动画,就像 jQuery 动画 $("#list").animate({scrollTop: 300 }, 2000);
,但是 没有 jQuery.
我遇到的一个大问题是,由于iron-list不会一次显示所有项目,因此我无法找到特定项目的scrollTop位置,因为它尚未在DOM中。
我在这里启动了一个 JSFiddle :http://jsfiddle.net/c52fakyf/2/
感谢您的帮助!
最佳答案
刚刚通过requestAnimationFrame学习动画,就思考了这个问题。我做了一个简单的动画方法:
animate: function(callbackObj, duration) {
var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
var startTime = 0, percentage = 0, animationTime = 0;
duration = duration*1000 || 1000;
var animate = function(timestamp) {
if (startTime === 0) {
startTime = timestamp;
} else {
animationTime = timestamp - startTime;
}
if (typeof callbackObj.start === 'function' && startTime === timestamp) {
callbackObj.start();
requestAnimationFrame(animate);
} else if (animationTime < duration) {
if (typeof callbackObj.progress === 'function') {
percentage = animationTime / duration;
callbackObj.progress(percentage);
}
requestAnimationFrame(animate);
} else if (typeof callbackObj.done === 'function'){
callbackObj.done();
}
};
return requestAnimationFrame(animate);
},
它基本上是一种递归方法,每次屏幕刷新时都会更新。该方法接受一个回调对象,该对象具有属性 .start、.progress 和 .done 下的函数。
我稍微修改了你的代码:
_autoScroll: function() {
var sequenceObj = {};
var seconds = 2;
var rangeInPixels = 500;
sequenceObj.progress = (function(percentage) {
this.$.itemList.scroll(0, this.easeInOutQuad(percentage)*rangeInPixels);
}).bind(this);
this.animate(sequenceObj, seconds);
},
我从Robert Penner的缓动函数中得到了easeInOut:
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
还有中提琴:
这并不完全是您所要求的,但这是您可以继续的一个开始。
关于javascript - Polymer 1.0 中带有铁列表的平滑自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886934/